Skip to content

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

[NPU] Add support to import a model from a memory mapped file (#31425)

Bogdan Pereanu20a34173eb71
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 77ba6fa5370..b1eb26f0888 100644
--- a/src/plugins/intel_npu/src/backend/include/zero_memory.hpp
+++ b/src/plugins/intel_npu/src/backend/include/zero_memory.hpp
@@ -11,14 +11,9 @@
#include <string>
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "intel_npu/utils/zero/zero_init.hpp"
-namespace {
-
-constexpr std::size_t STANDARD_PAGE_SIZE = 4096;
-
-} // namespace
-
namespace intel_npu {
namespace zeroMemory {
@@ -36,14 +31,14 @@ public:
* @param bytes The size in bytes to allocate
* @return Handle to the allocated resource
*/
- void* allocate(const size_t bytes, const size_t alignment = STANDARD_PAGE_SIZE) noexcept;
+ void* allocate(const size_t bytes, const size_t alignment = utils::STANDARD_PAGE_SIZE) noexcept;
/**
* @brief Releases handle and all associated memory resources which invalidates the handle.
* @param handle Pointer to allocated data
* @return false if handle cannot be released, otherwise - true.
*/
- bool deallocate(void* handle, const size_t bytes, size_t alignment = STANDARD_PAGE_SIZE) noexcept;
+ bool deallocate(void* handle, const size_t bytes, size_t alignment = utils::STANDARD_PAGE_SIZE) noexcept;
bool is_equal(const HostMemAllocator& other) const;
@@ -53,7 +48,7 @@ private:
Logger _logger;
ze_host_mem_alloc_flag_t _flag;
- static const std::size_t _alignment = STANDARD_PAGE_SIZE;
+ static const std::size_t _alignment = utils::STANDARD_PAGE_SIZE;
};
} // namespace zeroMemory
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 fd25d60a020..f6ec732b43d 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
@@ -139,6 +139,11 @@ void ZeroInferRequest::create_pipeline() {
batchSize = _graph->get_batch_size(_metadata, _userInputTensors.at(0), _graphInputDescriptors[0]);
}
for (size_t inputIndex = 0; inputIndex < _metadata.inputs.size(); ++inputIndex) {
+ if (_metadata.inputs.at(inputIndex).isMainInputWeights) {
+ // These values were set while running the "WeightlessGraph::init" method
+ continue;
+ }
+
if (is_batched_input(inputIndex) && batchSize.has_value()) {
if (_initStructs->getMutableCommandListExtVersion() >= ZE_MAKE_VERSION(1, 0)) {
_logger.debug("ZeroInferRequest::create_pipeline - tensors %s were already allocated",
diff --git a/src/plugins/intel_npu/src/common/include/intel_npu/common/device_helpers.hpp b/src/plugins/intel_npu/src/common/include/intel_npu/common/device_helpers.hpp
index ef60d387cd0..78d40d2f55f 100644
--- a/src/plugins/intel_npu/src/common/include/intel_npu/common/device_helpers.hpp
+++ b/src/plugins/intel_npu/src/common/include/intel_npu/common/device_helpers.hpp
@@ -9,6 +9,8 @@
#include "intel_npu/npu_private_properties.hpp"
+namespace intel_npu {
+
namespace utils {
bool isNPUDevice(const uint32_t deviceId);
uint32_t getSliceIdBySwDeviceId(const uint32_t swDevId);
@@ -17,3 +19,5 @@ std::string getCompilationPlatform(const std::string_view platform,
const std::string& deviceId,
std::vector<std::string> availableDevicesNames);
} // namespace utils
+
+} // namespace intel_npu
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
index 22ca65705dd..3fdf2d983b1 100644
--- 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
@@ -30,7 +30,7 @@ struct IONodeMetadata {
class IGraph : public std::enable_shared_from_this<IGraph> {
public:
- IGraph(ze_graph_handle_t handle, NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob);
+ IGraph(NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob);
/**
* @brief Writes the compiled model along with some metadata to the provided stream. The content of the stream can
@@ -52,7 +52,7 @@ public:
virtual ~IGraph() = default;
const NetworkMetadata& get_metadata() const;
- ze_graph_handle_t get_handle() const;
+ virtual ze_graph_handle_t get_handle() const = 0;
void update_network_name(std::string_view name);
@@ -103,7 +103,6 @@ protected:
* the plugin.
*/
- ze_graph_handle_t _handle = nullptr;
NetworkMetadata _metadata;
std::vector<ArgumentDescriptor> _input_descriptors;
diff --git a/src/plugins/intel_npu/src/common/src/device_helpers.cpp b/src/plugins/intel_npu/src/common/src/device_helpers.cpp
index 3981e590691..3b21815ae0c 100644
--- a/src/plugins/intel_npu/src/common/src/device_helpers.cpp
+++ b/src/plugins/intel_npu/src/common/src/device_helpers.cpp
@@ -6,6 +6,8 @@
#include "openvino/core/except.hpp"
+namespace intel_npu {
+
bool utils::isNPUDevice(const uint32_t deviceId) {
// bits 26-24 define interface type
// 000 - IPC
@@ -52,3 +54,5 @@ std::string utils::getCompilationPlatform(const std::string_view platform,
return utils::getPlatformByDeviceName(availableDevicesNames.at(0));
}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/common/src/igraph.cpp b/src/plugins/intel_npu/src/common/src/igraph.cpp
index f6093c0b371..9ef13b922b0 100644
--- a/src/plugins/intel_npu/src/common/src/igraph.cpp
+++ b/src/plugins/intel_npu/src/common/src/igraph.cpp
@@ -46,9 +46,8 @@ std::optional<size_t> IONodeMetadata::extract_batch(const ov::Shape& shape,
return std::nullopt; // TODO get layout from shape
}
-IGraph::IGraph(ze_graph_handle_t handle, NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob)
- : _handle(handle),
- _metadata(std::move(metadata)),
+IGraph::IGraph(NetworkMetadata metadata, const Config& config, std::optional<ov::Tensor> blob)
+ : _metadata(std::move(metadata)),
_blob(std::move(blob)),
_logger("IGraph", config.get<LOG_LEVEL>()) {}
@@ -56,10 +55,6 @@ const NetworkMetadata& IGraph::get_metadata() const {
return _metadata;
}
-ze_graph_handle_t IGraph::get_handle() const {
- return _handle;
-}
-
void IGraph::update_network_name(std::string_view name) {
_metadata.name = name;
}
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 7fc6af21836..e8d27652083 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
@@ -312,11 +312,6 @@ std::shared_ptr<ov::ITensor> SyncInferRequest::allocate_tensor(const IODescripto
const bool isInput,
const ov::Allocator& allocator,
const std::optional<std::size_t> batchSize) const {
- if (descriptor.isMainInputWeights) {
- // These values were set while running the "WeightlessGraph::init" method
- return nullptr;
- }
-
check_network_precision(descriptor.precision);
std::shared_ptr<ov::ITensor> tensor;
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp
index 0856e534229..29318a331c6 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/graph.hpp
@@ -20,11 +20,11 @@ class Graph : public IGraph {
public:
Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
- ze_graph_handle_t graphHandle,
+ const GraphDescriptor& graphDesc,
NetworkMetadata metadata,
std::optional<ov::Tensor> blob,
- const bool persistentBlob,
const Config& config,
+ const bool blobIsPersistent = false,
const ov::SoPtr<ICompiler>& compiler = {nullptr},
const bool calledFromWeightlessGraph = false);
@@ -35,6 +35,8 @@ public:
void set_argument_value(uint32_t argi, const void* argv) const override;
+ ze_graph_handle_t get_handle() const override;
+
void initialize(const Config& config) override;
~Graph() override;
@@ -46,10 +48,12 @@ protected:
std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
+ GraphDescriptor _graphDesc;
+
// 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;
- bool _persistentBlob = false;
+ bool _blobIsPersistent = false;
const ov::SoPtr<ICompiler> _compiler;
Logger _logger;
diff --git a/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp
index 5468735b214..2bba92d2dab 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/include/weightless_graph.hpp
@@ -23,15 +23,15 @@ class WeightlessGraph final : public Graph {
public:
WeightlessGraph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
- const bool persistentBlob,
- ze_graph_handle_t mainGraphHandle,
+ const GraphDescriptor& mainGraphDesc,
NetworkMetadata mainMetadata,
std::optional<ov::Tensor> mainBlob,
- const std::vector<ze_graph_handle_t>& initGraphHandles,
+ const std::vector<GraphDescriptor>& initGraphDesc,
std::vector<NetworkMetadata> initMetadata,
std::optional<std::vector<ov::Tensor>> initBlobs,
const std::shared_ptr<const ov::Model>& model,
const Config& config,
+ const bool blobIsPersistent = false,
const ov::SoPtr<ICompiler>& compiler = {nullptr});
/**
@@ -100,9 +100,10 @@ private:
*/
void set_weights_inputs();
- void release_init_blob(const size_t initIndex, const Config& config);
+ void release_init_blob(const size_t initIndex);
+ void release_graphs();
- std::vector<ze_graph_handle_t> _initsHandles;
+ std::vector<GraphDescriptor> _initsGraphDesc;
std::optional<std::vector<ov::Tensor>> _initBlobs;
std::vector<NetworkMetadata> _initsMetadata;
std::shared_ptr<const ov::Model> _model;
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
index 2fab7aadd53..fd7c713cacb 100644
--- 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
@@ -19,6 +19,13 @@ namespace intel_npu {
using SerializedIR = std::pair<size_t, std::shared_ptr<uint8_t>>;
+struct GraphDescriptor {
+ GraphDescriptor(ze_graph_handle_t handle = nullptr, void* data = nullptr);
+
+ ze_graph_handle_t _handle = nullptr;
+ void* _data = nullptr;
+};
+
/**
* Adapter to use CiD through ZeroAPI
*/
@@ -31,28 +38,29 @@ public:
std::unordered_set<std::string> queryGraph(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
const std::string& buildFlags) const;
- ze_graph_handle_t getGraphHandle(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
- const std::string& buildFlags,
- const uint32_t& flags) const;
- ze_graph_handle_t getGraphHandle(const uint8_t& data, size_t size) const;
+ GraphDescriptor getGraphDescriptor(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags) const;
- NetworkMetadata getNetworkMeta(ze_graph_handle_t graphHandle) const;
+ GraphDescriptor getGraphDescriptor(void* data, size_t size) const;
- _ze_result_t destroyGraph(ze_graph_handle_t graphHandle);
+ NetworkMetadata getNetworkMeta(GraphDescriptor& graphDescriptor) const;
+
+ void destroyGraph(GraphDescriptor& graphDescriptor);
std::string getCompilerSupportedOptions() const;
bool isOptionSupported(std::string optname) const;
- void getGraphBinary(ze_graph_handle_t graphHandle,
+ void getGraphBinary(const GraphDescriptor& graphDescriptor,
std::vector<uint8_t>& blob,
const uint8_t*& blobPtr,
size_t& blobSize) const;
- void setGraphArgumentValue(ze_graph_handle_t graphHandle, uint32_t argi_, const void* argv) const;
+ void setGraphArgumentValue(const GraphDescriptor& graphDescriptor, uint32_t argi_, const void* argv) const;
- void initializeGraph(ze_graph_handle_t graphHandle, uint32_t commandQueueGroupOrdinal) const;
+ void initializeGraph(const GraphDescriptor& graphDescriptor, uint32_t commandQueueGroupOrdinal) const;
private:
std::unordered_set<std::string> getQueryResultFromSupportedLayers(
@@ -66,6 +74,9 @@ private:
void initialize_graph_through_command_list(ze_graph_handle_t graphHandle, uint32_t commandQueueGroupOrdinal) const;
+ void* importCpuVa(void* data, size_t size, const uint32_t flags = 0) const;
+ bool releaseCpuVa(void* data);
+
std::shared_ptr<ZeroInitStructsHolder> _zeroInitStruct;
uint32_t _graphExtVersion;
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
index 29dd80f298f..11799ffa7d8 100644
--- 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
@@ -14,6 +14,7 @@
#include "intel_npu/config/options.hpp"
#include "intel_npu/prefix.hpp"
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/utils.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"
@@ -235,19 +236,18 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compile(const std::shared_ptr<con
}
_logger.debug("compile start");
- ze_graph_handle_t graphHandle = _zeGraphExt->getGraphHandle(std::move(serializedIR), buildFlags, flags);
+ auto graphDesc = _zeGraphExt->getGraphDescriptor(std::move(serializedIR), buildFlags, flags);
_logger.debug("compile end");
OV_ITT_TASK_NEXT(COMPILE_BLOB, "getNetworkMeta");
- auto networkMeta = _zeGraphExt->getNetworkMeta(graphHandle);
+ auto networkMeta = _zeGraphExt->getNetworkMeta(graphDesc);
networkMeta.name = model->get_friendly_name();
return std::make_shared<Graph>(_zeGraphExt,
_zeroInitStruct,
- graphHandle,
+ graphDesc,
std::move(networkMeta),
/* blob = */ std::nullopt,
- /* persistentBlob = */ false,
config);
}
@@ -298,8 +298,8 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(const std::shared_ptr<o
// the current call iteration.
std::vector<NetworkMetadata> initNetworkMetadata;
NetworkMetadata mainNetworkMetadata;
- std::vector<ze_graph_handle_t> initGraphHandles;
- ze_graph_handle_t mainGraphHandle;
+ std::vector<GraphDescriptor> initGraphDescriptors;
+ GraphDescriptor mainGraphHandle;
size_t callNumber = 0;
// Convention: run until the main schedule has been returned.
@@ -317,20 +317,20 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(const std::shared_ptr<o
buildFlags += serializeConfig(updatedConfig, compilerVersion);
_logger.debug("compile start");
- ze_graph_handle_t graphHandle = _zeGraphExt->getGraphHandle(serializedIR, buildFlags, flags);
+ auto graphDesc = _zeGraphExt->getGraphDescriptor(serializedIR, buildFlags, flags);
_logger.debug("compile end");
OV_ITT_TASK_NEXT(COMPILE_BLOB, "getNetworkMeta");
- NetworkMetadata networkMetadata = _zeGraphExt->getNetworkMeta(graphHandle);
+ NetworkMetadata networkMetadata = _zeGraphExt->getNetworkMeta(graphDesc);
if (isInitMetadata(networkMetadata)) {
networkMetadata.name = model->get_friendly_name() + "_init";
initNetworkMetadata.push_back(std::move(networkMetadata));
- initGraphHandles.push_back(graphHandle);
+ initGraphDescriptors.push_back(graphDesc);
} else {
networkMetadata.name = model->get_friendly_name() + "_main";
mainNetworkMetadata = std::move(networkMetadata);
- mainGraphHandle = graphHandle;
+ mainGraphHandle = graphDesc;
serializedIR = SerializedIR();
// By convention, the main schedule is the last result produced by the compiler
break;
@@ -347,11 +347,10 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::compileWS(const std::shared_ptr<o
return std::make_shared<WeightlessGraph>(_zeGraphExt,
_zeroInitStruct,
- /* persistentBlob = */ false,
mainGraphHandle,
std::move(mainNetworkMetadata),
/* mainBlob = */ std::nullopt,
- initGraphHandles,
+ initGraphDescriptors,
std::move(initNetworkMetadata),
/* initBlobs = */ std::nullopt,
model,
@@ -366,47 +365,49 @@ std::shared_ptr<IGraph> DriverCompilerAdapter::parse(
OV_ITT_TASK_CHAIN(PARSE_BLOB, itt::domains::NPUPlugin, "DriverCompilerAdapter", "parse");
_logger.debug("parse start");
- ze_graph_handle_t graphHandle =
- _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(mainBlob.data()), mainBlob.get_byte_size());
+ auto mainGraphDesc = _zeGraphExt->getGraphDescriptor(mainBlob.data(), mainBlob.get_byte_size());
_logger.debug("parse end");
OV_ITT_TASK_NEXT(PARSE_BLOB, "getNetworkMeta");
- auto networkMeta = _zeGraphExt->getNetworkMeta(graphHandle);
-
- const bool persistentBlob = config.get<LOADED_FROM_CACHE>();
+ auto networkMeta = _zeGraphExt->getNetworkMeta(mainGraphDesc);
if (!initBlobs.has_value()) {
return std::make_shared<Graph>(_zeGraphExt,
_zeroInitStruct,
- graphHandle,
+ mainGraphDesc,
std::move(networkMeta),
std::move(mainBlob),
- persistentBlob,
- config);
+ config,
+ config.has<LOADED_FROM_CACHE>()
+ ? config.get<LOADED_FROM_CACHE>()
+ : false); // exporting the blob when we get it from cache shall be available
}
// The presence of init schedules means weights separation has been enabled at compilation time. Use a specific
// "Graph" object as wrapper over all L0 handles.
- std::vector<ze_graph_handle_t> initGraphHandles;
+ std::vector<GraphDescriptor> initGraphDescriptors;
std::vector<NetworkMetadata> initMetadata;
+
for (const auto& initBlob : initBlobs.value()) {
- ze_graph_handle_t initGraphHandle =
- _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(initBlob.data()), initBlob.get_byte_size());
- initGraphHandles.push_back(initGraphHandle);
- initMetadata.push_back(_zeGraphExt->getNetworkMeta(initGraphHandle));
+ auto initGraphDesc = _zeGraphExt->getGraphDescriptor(initBlob.data(), initBlob.get_byte_size());
+
+ initGraphDescriptors.push_back(initGraphDesc);
+ initMetadata.push_back(_zeGraphExt->getNetworkMeta(initGraphDesc));
}
- return std::make_shared<WeightlessGraph>(_zeGraphExt,
- _zeroInitStruct,
- persistentBlob,
- graphHandle,
- std::move(networkMeta),
- std::move(mainBlob),
- initGraphHandles,
- std::move(initMetadata),
- std::move(initBlobs),
- model.value(),
- config);
+ return std::make_shared<WeightlessGraph>(
+ _zeGraphExt,
+ _zeroInitStruct,
+ mainGraphDesc,
+ std::move(networkMeta),
+ std::move(mainBlob),
+ initGraphDescriptors,
+ std::move(initMetadata),
+ std::move(initBlobs),
+ model.value(),
+ config,
+ config.has<LOADED_FROM_CACHE>() ? config.get<LOADED_FROM_CACHE>()
+ : false); // exporting the blob when we get it from cache shall be available
}
ov::SupportedOpsMap DriverCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp
index d45ce2fc493..6d8041744e4 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/graph.cpp
@@ -4,7 +4,10 @@
#include "graph.hpp"
+#include <iterator>
+
#include "intel_npu/config/options.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
#include "openvino/runtime/make_tensor.hpp"
@@ -12,17 +15,18 @@ namespace intel_npu {
Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
- ze_graph_handle_t graphHandle,
+ const GraphDescriptor& graphDesc,
NetworkMetadata metadata,
std::optional<ov::Tensor> blob,
- const bool persistentBlob,
const Config& config,
+ const bool blobIsPersistent,
const ov::SoPtr<ICompiler>& compiler,
const bool calledFromWeightlessGraph)
- : IGraph(graphHandle, std::move(metadata), config, std::move(blob)),
+ : IGraph(std::move(metadata), config, std::move(blob)),
_zeGraphExt(zeGraphExt),
_zeroInitStruct(zeroInitStruct),
- _persistentBlob(persistentBlob),
+ _graphDesc(graphDesc),
+ _blobIsPersistent(blobIsPersistent),
_compiler(compiler),
_logger("Graph", config.get<LOG_LEVEL>()) {
if (!config.get<CREATE_EXECUTOR>() || config.get<DEFER_WEIGHTS_LOAD>()) {
@@ -36,6 +40,10 @@ Graph::Graph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
}
}
+ze_graph_handle_t Graph::get_handle() const {
+ return _graphDesc._handle;
+}
+
std::pair<uint64_t, std::optional<std::vector<uint64_t>>> Graph::export_blob(std::ostream& stream) const {
const uint8_t* blobPtr = nullptr;
size_t blobSize;
@@ -47,7 +55,7 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> Graph::export_blob(std
if (_blob ==
std::nullopt) { // when compiling the model using Compiler in Driver, the blob is handled by the driver
- _zeGraphExt->getGraphBinary(_handle, blobVec, blobPtr, blobSize);
+ _zeGraphExt->getGraphBinary(_graphDesc, blobVec, blobPtr, blobSize);
} else { // in all other cases, the blob is handled by the plugin
blobPtr = static_cast<const uint8_t*>(_blob->data());
blobSize = _blob->get_byte_size();
@@ -73,8 +81,22 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> Graph::export_blob(std
str << "Blob size: " << blobSize << ", hash: " << std::hex << result;
_logger.info(str.str().c_str());
}
+
+ size_t size = utils::align_size_to_standarg_page_size(blobSize);
+ size_t paddingSize = size - blobSize;
+ if (paddingSize > 0) {
+ std::fill_n(std::ostream_iterator<char>(stream), paddingSize, 0);
+
+ if (!stream) {
+ _logger.error("Write padding to stream failed. Blob is broken!");
+ return std::make_pair(0, std::nullopt);
+ }
+
+ _logger.info("Blob size with padding: %ld", size);
+ }
+
_logger.info("Write blob to stream successfully.");
- return std::make_pair(blobSize, std::nullopt);
+ return std::make_pair(size, std::nullopt);
}
std::vector<ov::ProfilingInfo> Graph::process_profiling_output(const std::vector<uint8_t>& profData,
@@ -93,27 +115,27 @@ void Graph::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);
+ _zeGraphExt->setGraphArgumentValue(_graphDesc, argi, argv);
}
void Graph::initialize(const Config& config) {
_logger.debug("Graph initialize start");
- if (_zeGraphExt == nullptr || _handle == nullptr) {
+ if (_zeGraphExt == nullptr || _graphDesc._handle == nullptr) {
return;
}
_logger.debug("performing pfnGetProperties");
ze_graph_properties_t props{};
props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
- auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(_handle, &props);
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(_graphDesc._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);
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(_graphDesc._handle, index, &arg3);
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
@@ -157,7 +179,7 @@ void Graph::initialize(const Config& config) {
set_workload_type(config.get<WORKLOAD_TYPE>());
}
- _zeGraphExt->initializeGraph(_handle, _command_queue_group_ordinal);
+ _zeGraphExt->initializeGraph(_graphDesc, _command_queue_group_ordinal);
_logger.debug("Graph initialize finish");
// We are allowed to release the original blob because weights were loaded in NPU memory during
@@ -176,18 +198,14 @@ void Graph::initialize(const Config& config) {
}
bool Graph::release_blob(const Config& config) {
- if (_persistentBlob) {
- return false;
- }
-
- if (_blob == std::nullopt || _zeroInitStruct->getGraphDdiTable().version() < ZE_GRAPH_EXT_VERSION_1_8 ||
- config.get<PERF_COUNT>()) {
+ if (_graphDesc._data || _blobIsPersistent || _blob == std::nullopt ||
+ _zeroInitStruct->getGraphDdiTable().version() < ZE_MAKE_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);
+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(_graphDesc._handle, &properties);
if (~properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {
return false;
@@ -201,12 +219,8 @@ bool Graph::release_blob(const Config& config) {
Graph::~Graph() {
// make sure all the context-dependent components are destroyed before the zero context is destroyed
- if (_handle != nullptr) {
- auto result = _zeGraphExt->destroyGraph(_handle);
-
- if (ZE_RESULT_SUCCESS == result) {
- _handle = nullptr;
- }
+ if (_zeGraphExt != nullptr) {
+ _zeGraphExt->destroyGraph(_graphDesc);
}
if (!_last_submitted_event.empty()) {
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
index ae32c1b3629..56604505955 100644
--- 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
@@ -13,6 +13,7 @@
#include "intel_npu/config/options.hpp"
#include "intel_npu/npu_private_properties.hpp"
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_result.hpp"
#include "mem_usage.hpp"
@@ -98,28 +99,28 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compile(const std::shared_ptr<con
_logger.debug("compile end");
ov::Tensor tensor = make_tensor_from_vector(networkDesc.compiledNetwork);
- ze_graph_handle_t graphHandle = nullptr;
+ GraphDescriptor graphDesc;
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(*reinterpret_cast<const uint8_t*>(tensor.data()), tensor.get_byte_size());
+ graphDesc = _zeGraphExt->getGraphDescriptor(tensor.data(), tensor.get_byte_size());
} 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<Graph>(_zeGraphExt,
- _zeroInitStruct,
- graphHandle,
- std::move(networkDesc.metadata),
- std::move(tensor),
- /* persistentBlob = */ true,
- config,
- _compiler);
+ return std::make_shared<Graph>(
+ _zeGraphExt,
+ _zeroInitStruct,
+ graphDesc,
+ std::move(networkDesc.metadata),
+ std::move(tensor),
+ config,
+ /* persistentBlob = */ true, // exporting the blob shall be available in such a scenario
+ _compiler);
}
std::shared_ptr<IGraph> PluginCompilerAdapter::compileWS(const std::shared_ptr<ov::Model>& model,
@@ -200,53 +201,52 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::compileWS(const std::shared_ptr<o
_logger.debug("compile end");
ov::Tensor tensorMain = make_tensor_from_vector(mainNetworkDescription->compiledNetwork);
- ze_graph_handle_t mainGraphHandle = nullptr;
+ GraphDescriptor mainGraphDesc;
if (_zeGraphExt) {
// Depending on the config, we may get an error when trying to
// get the graph handle from the compiled network
try {
- mainGraphHandle = _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(tensorMain.data()),
- tensorMain.get_byte_size());
+ mainGraphDesc = _zeGraphExt->getGraphDescriptor(tensorMain.data(), tensorMain.get_byte_size());
} catch (...) {
_logger.info("Failed to obtain the level zero graph handle. Inference requests for this model are not "
"allowed. Only exports are available");
}
}
- std::vector<ze_graph_handle_t> initGraphHandles;
+ std::vector<GraphDescriptor> initGraphDescriptors;
std::vector<ov::Tensor> tensorsInits;
std::vector<NetworkMetadata> initNetworkMetadata;
- initGraphHandles.reserve(initNetworkDescriptions.size());
+ initGraphDescriptors.reserve(initNetworkDescriptions.size());
tensorsInits.reserve(initNetworkDescriptions.size());
initNetworkMetadata.reserve(initNetworkDescriptions.size());
for (auto& networkDesc : initNetworkDescriptions) {
ov::Tensor tensor = make_tensor_from_vector(networkDesc->compiledNetwork);
- ze_graph_handle_t graphHandle = nullptr;
+ GraphDescriptor initGraphDesc;
if (_zeGraphExt) {
try {
- graphHandle = _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(tensor.data()),
- tensor.get_byte_size());
+ initGraphDesc = _zeGraphExt->getGraphDescriptor(tensor.data(), tensor.get_byte_size());
} catch (...) {
}
}
- initGraphHandles.push_back(graphHandle);
+ initGraphDescriptors.push_back(initGraphDesc);
tensorsInits.push_back(std::move(tensor));
initNetworkMetadata.push_back(std::move(networkDesc->metadata));
}
- return std::make_shared<WeightlessGraph>(_zeGraphExt,
- _zeroInitStruct,
- /* persistentBlob = */ true,
- mainGraphHandle,
- std::move(mainNetworkDescription->metadata),
- std::move(tensorMain),
- initGraphHandles,
- std::move(initNetworkMetadata),
- tensorsInits,
- model,
- config,
- _compiler);
+ return std::make_shared<WeightlessGraph>(
+ _zeGraphExt,
+ _zeroInitStruct,
+ mainGraphDesc,
+ std::move(mainNetworkDescription->metadata),
+ std::move(tensorMain),
+ initGraphDescriptors,
+ std::move(initNetworkMetadata),
+ tensorsInits,
+ model,
+ config,
+ /* persistentBlob = */ true, // exporting the blob shall be available in such a scenario
+ _compiler);
}
std::shared_ptr<IGraph> PluginCompilerAdapter::parse(
@@ -264,32 +264,28 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::parse(
network.clear();
network.shrink_to_fit();
- ze_graph_handle_t graphHandle = nullptr;
-
- if (_zeGraphExt) {
- graphHandle =
- _zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(mainBlob.data()), mainBlob.get_byte_size());
- }
+ auto mainGraphDesc = _zeGraphExt->getGraphDescriptor(mainBlob.data(), mainBlob.get_byte_size());
_logger.debug("main schedule parse end");
- const bool persistentBlob = config.get<LOADED_FROM_CACHE>();
-
if (!initBlobs.has_value()) {
return std::make_shared<Graph>(_zeGraphExt,
_zeroInitStruct,
- graphHandle,
+ mainGraphDesc,
std::move(networkMeta),
std::move(mainBlob),
- persistentBlob,
config,
+ config.has<LOADED_FROM_CACHE>()
+ ? config.get<LOADED_FROM_CACHE>()
+ : false, // exporting the blob when we get it from cache shall be available
_compiler);
}
// The presence of init schedules means weights separation has been enabled at compilation time. Use a specific
// "Graph" object as wrapper over all L0 handles.
- std::vector<ze_graph_handle_t> initGraphHandles;
+ std::vector<GraphDescriptor> initGraphDescriptors;
std::vector<NetworkMetadata> initMetadata;
+
for (const auto& initBlob : initBlobs.value()) {
network.reserve(initBlob.get_byte_size());
network.assign(reinterpret_cast<const uint8_t*>(initBlob.data()),
@@ -299,24 +295,27 @@ std::shared_ptr<IGraph> PluginCompilerAdapter::parse(
network.shrink_to_fit();
if (_zeGraphExt) {
- initGraphHandles.push_back(_zeGraphExt->getGraphHandle(*reinterpret_cast<const uint8_t*>(initBlob.data()),
- initBlob.get_byte_size()));
+ auto initGraphDesc = _zeGraphExt->getGraphDescriptor(initBlob.data(), initBlob.get_byte_size());
+
+ initGraphDescriptors.push_back(initGraphDesc);
}
}
_logger.debug("init schedules parse end");
- return std::make_shared<WeightlessGraph>(_zeGraphExt,
- _zeroInitStruct,
- persistentBlob,
- graphHandle,
- std::move(networkMeta),
- std::move(mainBlob),
- initGraphHandles,
- std::move(initMetadata),
- std::move(initBlobs),
- model.value(),
- config,
- _compiler);
+ return std::make_shared<WeightlessGraph>(
+ _zeGraphExt,
+ _zeroInitStruct,
+ mainGraphDesc,
+ std::move(networkMeta),
+ std::move(mainBlob),
+ initGraphDescriptors,
+ std::move(initMetadata),
+ std::move(initBlobs),
+ model.value(),
+ config,
+ config.has<LOADED_FROM_CACHE>() ? config.get<LOADED_FROM_CACHE>()
+ : false, // exporting the blob when we get it from cache shall be available
+ _compiler);
}
ov::SupportedOpsMap PluginCompilerAdapter::query(const std::shared_ptr<const ov::Model>& model,
diff --git a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp
index a74038ebf16..e8fc08ef79d 100644
--- a/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp
+++ b/src/plugins/intel_npu/src/compiler_adapter/src/weightless_graph.cpp
@@ -5,11 +5,13 @@
#include "weightless_graph.hpp"
#include <condition_variable>
+#include <iterator>
#include <mutex>
#include <queue>
#include "intel_npu/config/options.hpp"
#include "intel_npu/prefix.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "openvino/core/model.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
#include "openvino/core/type/element_iterator.hpp"
@@ -147,26 +149,26 @@ void merge_two_maps(std::unordered_map<std::string, std::shared_ptr<ov::ITensor>
WeightlessGraph::WeightlessGraph(const std::shared_ptr<ZeGraphExtWrappers>& zeGraphExt,
const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct,
- const bool persistentBlob,
- ze_graph_handle_t mainGraphHandle,
+ const GraphDescriptor& mainGraphDesc,
NetworkMetadata mainMetadata,
std::optional<ov::Tensor> mainBlob,
- const std::vector<ze_graph_handle_t>& initGraphHandles,
+ const std::vector<GraphDescriptor>& initGraphDesc,
std::vector<NetworkMetadata> initMetadata,
std::optional<std::vector<ov::Tensor>> initBlobs,
const std::shared_ptr<const ov::Model>& model,
const Config& config,
+ const bool blobIsPersistent,
const ov::SoPtr<ICompiler>& compiler)
: Graph(zeGraphExt,
zeroInitStruct,
- mainGraphHandle,
+ mainGraphDesc,
std::move(mainMetadata),
std::move(mainBlob),
- persistentBlob,
config,
+ blobIsPersistent,
compiler,
true),
- _initsHandles(initGraphHandles),
+ _initsGraphDesc(initGraphDesc),
_initBlobs(std::move(initBlobs)),
_initsMetadata(std::move(initMetadata)),
_model(model) {
@@ -188,14 +190,15 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> WeightlessGraph::expor
std::uint32_t totalResult = 1171117u;
totalResult = ((totalResult << 7) + totalResult);
- const auto writeToStream = [&](ze_graph_handle_t handle, const std::optional<ov::Tensor>& blobTensor) -> uint64_t {
+ const auto writeToStream = [&](GraphDescriptor _graphDesc,
+ const std::optional<ov::Tensor>& blobTensor) -> uint64_t {
uint64_t blobSize;
const uint8_t* blobRawPtr = nullptr;
std::vector<uint8_t> blob;
if (blobTensor == std::nullopt) {
// when compiling the model using Compiler in Driver, the blob is handled by the driver
- _zeGraphExt->getGraphBinary(handle, blob, blobRawPtr, blobSize);
+ _zeGraphExt->getGraphBinary(_graphDesc, blob, blobRawPtr, blobSize);
} else {
// in all other cases, the blob is handled by the plugin
blobRawPtr = static_cast<const uint8_t*>(blobTensor->data());
@@ -229,18 +232,31 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> WeightlessGraph::expor
_logger.info(str.str().c_str());
}
- return blobSize;
+ size_t size = utils::align_size_to_standarg_page_size(blobSize);
+ size_t paddingSize = size - blobSize;
+ if (paddingSize > 0) {
+ std::fill_n(std::ostream_iterator<char>(stream), paddingSize, 0);
+
+ if (!stream) {
+ _logger.error("Write padding to stream failed. Blob is broken!");
+ return 0;
+ }
+
+ _logger.info("Blob size with padding: %ld", size);
+ }
+
+ return size;
};
// By convention, first write the main part
- uint64_t mainBlobSize = writeToStream(_handle, _blob);
+ uint64_t mainBlobSize = writeToStream(_graphDesc, _blob);
uint64_t totalBlobSize = mainBlobSize;
++blobIndex;
// Then the init schedules
std::vector<uint64_t> initSizes;
- for (size_t initIndex = 0; initIndex < _initsHandles.size(); ++initIndex) {
- uint64_t initBlobSize = writeToStream(_initsHandles.at(initIndex),
+ for (size_t initIndex = 0; initIndex < _initsGraphDesc.size(); ++initIndex) {
+ uint64_t initBlobSize = writeToStream(_initsGraphDesc.at(initIndex)._handle,
_initBlobs.has_value() && _initBlobs->at(initIndex)
? std::make_optional(_initBlobs->at(initIndex))
: std::nullopt);
@@ -259,7 +275,7 @@ std::pair<uint64_t, std::optional<std::vector<uint64_t>>> WeightlessGraph::expor
void WeightlessGraph::initialize(const Config& config) {
// Simplified version for init schedules
- const size_t numberOfInits = _initsHandles.size();
+ const size_t numberOfInits = _initsGraphDesc.size();
_initsInputDescriptors.resize(numberOfInits);
_initsOutputDescriptors.resize(numberOfInits);
_initsCommandQueueOrdinals.resize(numberOfInits);
@@ -268,8 +284,6 @@ void WeightlessGraph::initialize(const Config& config) {
for (size_t initIndex = 0; initIndex < numberOfInits; ++initIndex) {
_logger.debug("WeightlessGraph initialize start, init schedule ", initIndex);
-
- ze_graph_handle_t initHandle = _initsHandles.at(initIndex);
std::vector<ArgumentDescriptor>& initInputDescriptors = _initsInputDescriptors.at(initIndex);
std::vector<ArgumentDescriptor>& initOutputDescriptors = _initsOutputDescriptors.at(initIndex);
uint32_t& initCommandQueueOrdinal = _initsCommandQueueOrdinals.at(initIndex);
@@ -278,14 +292,18 @@ void WeightlessGraph::initialize(const Config& config) {
_logger.debug("performing pfnGetProperties");
ze_graph_properties_t props{};
props.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
- auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(initHandle, &props);
+ auto result =
+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties(_initsGraphDesc.at(initIndex)._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(initHandle, index, &arg3);
+ auto result =
+ _zeroInitStruct->getGraphDdiTable().pfnGetArgumentProperties3(_initsGraphDesc.at(initIndex)._handle,
+ index,
+ &arg3);
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetArgumentProperties3", result, _zeroInitStruct->getGraphDdiTable());
if (arg3.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT) {
@@ -301,13 +319,13 @@ void WeightlessGraph::initialize(const Config& config) {
initCommandQueueOrdinal = zeroUtils::findCommandQueueGroupOrdinal(_zeroInitStruct->getDevice(),
ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE);
- _zeGraphExt->initializeGraph(initHandle, initCommandQueueOrdinal);
+ _zeGraphExt->initializeGraph(_initsGraphDesc.at(initIndex), initCommandQueueOrdinal);
_logger.debug("WeightlessGraph initialize finish, init schedule ", initIndex);
// 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.
- release_init_blob(initIndex, config);
+ release_init_blob(initIndex);
}
// Create a single command queue for all weights initialization schedules
@@ -345,6 +363,11 @@ void WeightlessGraph::initialize(const Config& config) {
run_init_multi_threaded();
#endif
+ if (_initBlobs != std::nullopt) { // Do not release the graph when compiling a model on the CiD path, and we don't
+ // have a blob. We may need it to export later.
+ release_graphs();
+ }
+
_initsInputDescriptors.clear();
_initsOutputDescriptors.clear();
_initsCommandQueueOrdinals.clear();
@@ -445,7 +468,7 @@ WeightlessGraph::OutputData WeightlessGraph::allocate_outputs(const size_t initI
void WeightlessGraph::run_init_single_threaded() {
auto constants = get_all_constants_in_topological_order(_model, _logger);
- for (size_t initIndex = 0; initIndex < _initsHandles.size(); ++initIndex) {
+ for (size_t initIndex = 0; initIndex < _initsGraphDesc.size(); ++initIndex) {
auto [initInputsViewTensors, initInputsAllocatedTensor] = allocate_inputs(initIndex, constants);
// We don't need these anymore, potentially save some memory
@@ -464,7 +487,7 @@ void WeightlessGraph::run_init_single_threaded() {
}
void WeightlessGraph::run_init_multi_threaded() {
- if (_initsHandles.size() == 1) {
+ if (_initsGraphDesc.size() == 1) {
_logger.info("::run_init_multi_threaded() for single init - fallback to ::runInit()");
run_init_single_threaded();
return;
@@ -507,7 +530,7 @@ void WeightlessGraph::run_init_multi_threaded() {
},
_logger);
- multiThreadedRunner.callForAllAndWait(_initsHandles.size());
+ multiThreadedRunner.callForAllAndWait(_initsGraphDesc.size());
_model = nullptr;
}
@@ -527,17 +550,18 @@ void WeightlessGraph::create_pipeline(const size_t initIndex,
size_t io_index = 0;
for (const auto& desc : _initsInputDescriptors.at(initIndex)) {
void* data = inputTensors.at(io_index++)->data();
- _zeGraphExt->setGraphArgumentValue(_initsHandles.at(initIndex), desc.idx, static_cast<unsigned char*>(data));
+ _zeGraphExt->setGraphArgumentValue(_initsGraphDesc.at(initIndex), desc.idx, static_cast<unsigned char*>(data));
}
io_index = 0;
for (const auto& desc : _initsOutputDescriptors.at(initIndex)) {
void* data = outputTensors.at(io_index++)->data();
- _zeGraphExt->setGraphArgumentValue(_initsHandles.at(initIndex), desc.idx, static_cast<unsigned char*>(data));
+ _zeGraphExt->setGraphArgumentValue(_initsGraphDesc.at(initIndex), desc.idx, static_cast<unsigned char*>(data));
}
- _initsCommandLists.at(initIndex)->appendGraphExecute(static_cast<ze_graph_handle_t>(_initsHandles.at(initIndex)),
- nullptr);
+ _initsCommandLists.at(initIndex)->appendGraphExecute(
+ static_cast<ze_graph_handle_t>(_initsGraphDesc.at(initIndex)._handle),
+ nullptr);
_logger.debug("Init Pipeline - initialize completed");
}
@@ -570,34 +594,42 @@ void WeightlessGraph::set_weights_inputs() {
}
}
-void WeightlessGraph::release_init_blob(const size_t initIndex, const Config& config) {
- if (_initBlobs == std::nullopt || config.get<PERF_COUNT>()) {
+void WeightlessGraph::release_init_blob(const size_t initIndex) {
+ if (_initsGraphDesc[initIndex]._data || _blobIsPersistent || _initBlobs == std::nullopt) {
return;
}
ze_graph_properties_2_t properties = {};
properties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
- _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(_initsHandles.at(initIndex), &properties);
+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(_initsGraphDesc.at(initIndex)._handle, &properties);
if (~properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {
return;
}
_initBlobs->at(initIndex) = ov::Tensor();
- _logger.debug("Blob is released");
+ _logger.debug("Init blob is released");
}
-WeightlessGraph::~WeightlessGraph() {
- // make sure all the context-dependent components are destroyed before the zero context is destroyed
- for (auto& initHandle : _initsHandles) {
- if (initHandle != nullptr) {
- auto result = _zeGraphExt->destroyGraph(initHandle);
+void WeightlessGraph::release_graphs() {
+ size_t initIndex = 0;
+ if (_zeGraphExt != nullptr) {
+ for (auto& initGraphDesc : _initsGraphDesc) {
+ _zeGraphExt->destroyGraph(initGraphDesc);
- if (ZE_RESULT_SUCCESS == result) {
- initHandle = nullptr;
+ if (!_blobIsPersistent && _initBlobs != std::nullopt && _initBlobs->at(initIndex)) {
+ _initBlobs->at(initIndex) = ov::Tensor();
}
+
+ initIndex++;
}
}
+ _logger.debug("Init graphs are destroyed");
+}
+
+WeightlessGraph::~WeightlessGraph() {
+ // make sure all the context-dependent components are destroyed before the zero context is destroyed
+ release_graphs();
}
} // namespace intel_npu
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
index 7ddab1089b4..554bb5c9dbc 100644
--- 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
@@ -4,11 +4,14 @@
#include "ze_graph_ext_wrappers.hpp"
+#include <ze_mem_import_system_memory_ext.h>
+
#include <regex>
#include <string_view>
#include "intel_npu/config/options.hpp"
#include "intel_npu/prefix.hpp"
+#include "intel_npu/utils/utils.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"
@@ -43,6 +46,8 @@ constexpr std::size_t DEFAULT_BATCH_SIZE = 1;
namespace intel_npu {
+GraphDescriptor::GraphDescriptor(ze_graph_handle_t handle, void* data) : _handle(handle), _data(data) {}
+
ZeGraphExtWrappers::ZeGraphExtWrappers(const std::shared_ptr<ZeroInitStructsHolder>& zeroInitStruct)
: _zeroInitStruct(zeroInitStruct),
_graphExtVersion(zeroInitStruct->getGraphDdiTable().version()),
@@ -63,24 +68,48 @@ ZeGraphExtWrappers::~ZeGraphExtWrappers() {
_logger.debug("Obj destroyed");
}
-_ze_result_t ZeGraphExtWrappers::destroyGraph(ze_graph_handle_t graphHandle) {
- _logger.debug("destroyGraph - perform pfnDestroy");
- auto result = _zeroInitStruct->getGraphDdiTable().pfnDestroy(graphHandle);
+bool ZeGraphExtWrappers::releaseCpuVa(void* data) {
+ _logger.debug("destroyGraph - perform zeMemFree");
+ auto result = zeMemFree(_zeroInitStruct->getContext(), data);
if (ZE_RESULT_SUCCESS != result) {
- _logger.error("failed to destroy graph handle. L0 pfnDestroy result: %s, code %#X",
+ _logger.error("failed to free L0 memory result: %s, code %#X - %s",
ze_result_to_string(result).c_str(),
- uint64_t(result));
+ uint64_t(result),
+ ze_result_to_description(result).c_str());
+
+ return false;
}
- return result;
+ return true;
+}
+
+void ZeGraphExtWrappers::destroyGraph(GraphDescriptor& graphDescriptor) {
+ if (graphDescriptor._handle) {
+ _logger.debug("destroyGraph - perform pfnDestroy");
+
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnDestroy(graphDescriptor._handle);
+ 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));
+ } else {
+ graphDescriptor._handle = nullptr;
+ }
+
+ if (graphDescriptor._data != nullptr) {
+ if (releaseCpuVa(graphDescriptor._data)) {
+ graphDescriptor._data = nullptr;
+ }
+ }
+ }
}
-void ZeGraphExtWrappers::getGraphBinary(ze_graph_handle_t graphHandle,
+void ZeGraphExtWrappers::getGraphBinary(const GraphDescriptor& graphDescriptor,
std::vector<uint8_t>& blob,
const uint8_t*& blobPtr,
size_t& blobSize) const {
- if (graphHandle == nullptr) {
+ if (graphDescriptor._handle == nullptr) {
OPENVINO_THROW("Graph handle is null");
}
@@ -89,7 +118,8 @@ void ZeGraphExtWrappers::getGraphBinary(ze_graph_handle_t graphHandle,
if (UseCopyForNativeBinary(_graphExtVersion)) {
// Get blob size first
_logger.debug("getGraphBinary - perform pfnGetNativeBinary to get size");
- auto result = _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary(graphHandle, &blobSize, nullptr);
+ auto result =
+ _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary(graphDescriptor._handle, &blobSize, nullptr);
blob.resize(blobSize);
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob size, Failed to compile network.",
result,
@@ -97,7 +127,8 @@ void ZeGraphExtWrappers::getGraphBinary(ze_graph_handle_t graphHandle,
// Get blob data
_logger.debug("getGraphBinary - perform pfnGetNativeBinary to get data");
- result = _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary(graphHandle, &blobSize, blob.data());
+ result =
+ _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary(graphDescriptor._handle, &blobSize, blob.data());
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob data, Failed to compile network.",
result,
_zeroInitStruct->getGraphDdiTable());
@@ -106,37 +137,41 @@ void ZeGraphExtWrappers::getGraphBinary(ze_graph_handle_t graphHandle,
} else {
// Get blob ptr and size
_logger.debug("getGraphBinary - perform pfnGetNativeBinary2 to get size and data");
- auto result = _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary2(graphHandle, &blobSize, &blobPtr);
+ auto result =
+ _zeroInitStruct->getGraphDdiTable().pfnGetNativeBinary2(graphDescriptor._handle, &blobSize, &blobPtr);
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnGetNativeBinary get blob size, Failed to compile network.",
result,
_zeroInitStruct->getGraphDdiTable());
}
}
-void ZeGraphExtWrappers::setGraphArgumentValue(ze_graph_handle_t graphHandle, uint32_t argi, const void* argv) const {
+void ZeGraphExtWrappers::setGraphArgumentValue(const GraphDescriptor& graphDescriptor,
+ uint32_t argi,
+ const void* argv) const {
_logger.debug("setGraphArgumentValue - perform pfnSetArgumentValue");
- auto result = _zeroInitStruct->getGraphDdiTable().pfnSetArgumentValue(graphHandle, argi, argv);
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnSetArgumentValue(graphDescriptor._handle, argi, argv);
THROW_ON_FAIL_FOR_LEVELZERO_EXT("zeGraphSetArgumentValue", result, _zeroInitStruct->getGraphDdiTable());
}
-void ZeGraphExtWrappers::initializeGraph(ze_graph_handle_t graphHandle, uint32_t commandQueueGroupOrdinal) const {
+void ZeGraphExtWrappers::initializeGraph(const GraphDescriptor& graphDescriptor,
+ uint32_t commandQueueGroupOrdinal) const {
if (_zeroInitStruct->getGraphDdiTable().version() < ZE_GRAPH_EXT_VERSION_1_8) {
_logger.debug("Use initialize_graph_through_command_list for ext version smaller than 1.8");
- initialize_graph_through_command_list(graphHandle, commandQueueGroupOrdinal);
+ initialize_graph_through_command_list(graphDescriptor._handle, commandQueueGroupOrdinal);
} else {
_logger.debug("Initialize graph based on graph properties for ext version larger than 1.8");
ze_graph_properties_2_t properties = {};
properties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
_logger.debug("initializeGraph - perform pfnGetProperties2");
- _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(graphHandle, &properties);
+ _zeroInitStruct->getGraphDdiTable().pfnGetProperties2(graphDescriptor._handle, &properties);
if (properties.initStageRequired & ZE_GRAPH_STAGE_INITIALIZE) {
_logger.debug("initializeGraph - perform pfnGraphInitialize");
- _zeroInitStruct->getGraphDdiTable().pfnGraphInitialize(graphHandle);
+ _zeroInitStruct->getGraphDdiTable().pfnGraphInitialize(graphDescriptor._handle);
}
if (properties.initStageRequired & ZE_GRAPH_STAGE_COMMAND_LIST_INITIALIZE) {
- initialize_graph_through_command_list(graphHandle, commandQueueGroupOrdinal);
+ initialize_graph_through_command_list(graphDescriptor._handle, commandQueueGroupOrdinal);
}
}
}
@@ -280,9 +315,46 @@ std::unordered_set<std::string> ZeGraphExtWrappers::queryGraph(std::pair<size_t,
return std::unordered_set<std::string>();
}
-ze_graph_handle_t ZeGraphExtWrappers::getGraphHandle(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
- const std::string& buildFlags,
- const uint32_t& flags) const {
+void* ZeGraphExtWrappers::importCpuVa(void* data, size_t size, const uint32_t flags) const {
+ if (_graphExtVersion < ZE_MAKE_VERSION(1, 13) ||
+ !utils::memory_and_size_aligned_to_standard_page_size(data, size)) {
+ return nullptr;
+ }
+
+ ze_device_external_memory_properties_t externalMemorydDesc = {};
+ externalMemorydDesc.stype = ZE_STRUCTURE_TYPE_DEVICE_EXTERNAL_MEMORY_PROPERTIES;
+
+ auto res = zeDeviceGetExternalMemoryProperties(_zeroInitStruct->getDevice(), &externalMemorydDesc);
+ if ((res != ZE_RESULT_SUCCESS) ||
+ ((externalMemorydDesc.memoryAllocationImportTypes & ZE_EXTERNAL_MEMORY_TYPE_FLAG_STANDARD_ALLOCATION) == 0)) {
+ return nullptr;
+ }
+
+ _ze_external_memory_import_system_memory_t memory_import = {ZE_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMPORT_SYSTEM_MEMORY,
+ nullptr,
+ data,
+ size};
+
+ void* importedNpuData = nullptr;
+
+ ze_host_mem_alloc_desc_t memAllocDesc = {ZE_STRUCTURE_TYPE_DEVICE_MEM_ALLOC_DESC, &memory_import, flags};
+ res =
+ zeMemAllocHost(_zeroInitStruct->getContext(), &memAllocDesc, size, utils::STANDARD_PAGE_SIZE, &importedNpuData);
+
+ if (res == ZE_RESULT_SUCCESS) {
+ return importedNpuData;
+ }
+
+ _logger.debug("Got an error when importing a CPUVA: %s, code %#X - %s",
+ ze_result_to_string(res).c_str(),
+ uint64_t(res),
+ ze_result_to_description(res).c_str());
+ return nullptr;
+}
+
+GraphDescriptor ZeGraphExtWrappers::getGraphDescriptor(std::pair<size_t, std::shared_ptr<uint8_t>> serializedIR,
+ const std::string& buildFlags,
+ const uint32_t& flags) const {
ze_graph_handle_t graphHandle = nullptr;
if (NotSupportGraph2(_graphExtVersion)) {
// For ext version <1.5, calling pfnCreate api in _zeroInitStruct->getGraphDdiTable()
@@ -293,7 +365,7 @@ ze_graph_handle_t ZeGraphExtWrappers::getGraphHandle(std::pair<size_t, std::shar
serializedIR.second.get(),
buildFlags.c_str()};
- _logger.debug("getGraphHandle - perform pfnCreate");
+ _logger.debug("getGraphDescriptor - perform pfnCreate");
// Create querynetwork handle
auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate(_zeroInitStruct->getContext(),
_zeroInitStruct->getDevice(),
@@ -310,7 +382,7 @@ ze_graph_handle_t ZeGraphExtWrappers::getGraphHandle(std::pair<size_t, std::shar
buildFlags.c_str(),
flags};
- _logger.debug("getGraphHandle - perform pfnCreate2");
+ _logger.debug("getGraphDescriptor - perform pfnCreate2");
// Create querynetwork handle
auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate2(_zeroInitStruct->getContext(),
_zeroInitStruct->getDevice(),
@@ -318,27 +390,42 @@ ze_graph_handle_t ZeGraphExtWrappers::getGraphHandle(std::pair<size_t, std::shar
&graphHandle);
THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate2", result, _zeroInitStruct->getGraphDdiTable());
}
- return graphHandle;
+ return GraphDescriptor{graphHandle};
}
-ze_graph_handle_t ZeGraphExtWrappers::getGraphHandle(const uint8_t& blobData, size_t blobSize) const {
+GraphDescriptor ZeGraphExtWrappers::getGraphDescriptor(void* blobData, size_t blobSize) const {
ze_graph_handle_t graphHandle = nullptr;
if (blobSize == 0) {
OPENVINO_THROW("Empty blob");
}
- ze_graph_desc_t desc =
- {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES, nullptr, ZE_GRAPH_FORMAT_NATIVE, blobSize, &blobData, nullptr};
+ uint32_t flags = 0;
+
+ void* npuMemory = importCpuVa(blobData, blobSize, ZE_HOST_MEM_ALLOC_FLAG_BIAS_WRITE_COMBINED);
+
+ if (npuMemory) {
+ _logger.debug("getGraphDescriptor - set ZE_GRAPH_FLAG_INPUT_GRAPH_PERSISTENT");
+ flags = ZE_GRAPH_FLAG_INPUT_GRAPH_PERSISTENT;
+ }
+
+ ze_graph_desc_2_t desc = {ZE_STRUCTURE_TYPE_GRAPH_DESC_PROPERTIES,
+ nullptr,
+ ZE_GRAPH_FORMAT_NATIVE,
+ blobSize,
+ reinterpret_cast<const uint8_t*>(blobData),
+ nullptr,
+ flags};
+
+ _logger.debug("getGraphDescriptor - perform pfnCreate2");
- _logger.debug("getGraphHandle - perform pfnCreate");
- auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate(_zeroInitStruct->getContext(),
- _zeroInitStruct->getDevice(),
- &desc,
- &graphHandle);
- THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate", result, _zeroInitStruct->getGraphDdiTable());
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnCreate2(_zeroInitStruct->getContext(),
+ _zeroInitStruct->getDevice(),
+ &desc,
+ &graphHandle);
+ THROW_ON_FAIL_FOR_LEVELZERO_EXT("pfnCreate2", result, _zeroInitStruct->getGraphDdiTable());
- return graphHandle;
+ return GraphDescriptor{graphHandle, npuMemory};
}
/**
@@ -487,16 +574,16 @@ void ZeGraphExtWrappers::getMetadata(ze_graph_handle_t graphHandle,
}
}
-NetworkMetadata ZeGraphExtWrappers::getNetworkMeta(ze_graph_handle_t graphHandle) const {
+NetworkMetadata ZeGraphExtWrappers::getNetworkMeta(GraphDescriptor& graphDescriptor) const {
ze_graph_properties_t graphProperties = {};
graphProperties.stype = ZE_STRUCTURE_TYPE_GRAPH_PROPERTIES;
_logger.debug("getNetworkMeta - perform pfnGetProperties");
- auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(graphHandle, &graphProperties);
+ auto result = _zeroInitStruct->getGraphDdiTable().pfnGetProperties(graphDescriptor._handle, &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);
+ getMetadata(graphDescriptor._handle, index, meta.inputs, meta.outputs);
}
// TODO: support this information in CiD [track: E#33479]
meta.numStreams = 1;
diff --git a/src/plugins/intel_npu/src/plugin/include/metadata.hpp b/src/plugins/intel_npu/src/plugin/include/metadata.hpp
index 25fa58921ad..1289c8b6152 100644
--- a/src/plugins/intel_npu/src/plugin/include/metadata.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/metadata.hpp
@@ -34,15 +34,6 @@ public:
*/
virtual void write(std::ostream& stream) = 0;
- /**
- * @brief Adds the size of the binary object and the magic string to the end of the stream.
- * @details This should be called after the "write" method in order to conclude writing the metadata into the given
- * stream.
- * @note This operation was detached from "write" since "write" writes at the beginning of the stream, while this
- * method writes at the end. This change allows better extension of class hierarchy.
- */
- void append_blob_size_and_magic(std::ostream& stream);
-
virtual bool is_compatible() = 0;
virtual uint64_t get_blob_size() const;
@@ -56,6 +47,8 @@ public:
static std::streampos getFileSize(std::istream& stream);
+ virtual size_t get_metadata_size() const = 0;
+
/**
* @brief Returns a uint32_t value which represents two uint16_t values concatenated.
* @details Convention for bumping the metadata version:
@@ -85,6 +78,15 @@ public:
}
protected:
+ /**
+ * @brief Adds the size of the binary object and the magic string to the end of the stream.
+ * @details This should be called after the "write" method in order to conclude writing the metadata into the given
+ * stream.
+ * @note This operation was detached from "write" since "write" writes at the beginning of the stream, while this
+ * method writes at the end. This change allows better extension of class hierarchy.
+ */
+ void append_padding_blob_size_and_magic(std::ostream& stream);
+
uint32_t _version;
uint64_t _blobDataSize;
};
@@ -150,6 +152,8 @@ public:
uint16_t get_patch() const;
+ size_t get_openvino_version_size() const;
+
bool operator!=(const OpenvinoVersion& version);
private:
@@ -206,6 +210,8 @@ public:
std::optional<std::vector<uint64_t>> get_init_sizes() const override;
+ size_t get_metadata_size() const override;
+
protected:
OpenvinoVersion _ovVersion;
};
@@ -236,8 +242,11 @@ public:
std::optional<std::vector<uint64_t>> get_init_sizes() const override;
+ size_t get_metadata_size() const override;
+
private:
std::optional<std::vector<uint64_t>> _initSizes;
+ uint64_t _numberOfInits = 0;
};
/**
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 0ca9c625abd..4e29dce910f 100644
--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
@@ -90,9 +90,8 @@ void CompiledModel::export_model(std::ostream& stream) const {
auto [blobSizesBeforeVersioning, initBlobSizes] = _graph->export_blob(stream);
- auto meta = Metadata<CURRENT_METADATA_VERSION>(blobSizesBeforeVersioning, CURRENT_OPENVINO_VERSION, initBlobSizes);
- meta.write(stream);
- meta.append_blob_size_and_magic(stream);
+ Metadata<CURRENT_METADATA_VERSION>(blobSizesBeforeVersioning, CURRENT_OPENVINO_VERSION, initBlobSizes)
+ .write(stream);
}
std::shared_ptr<const ov::Model> CompiledModel::get_runtime_model() const {
diff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cpp
index c2fdee9d454..40714d87ce3 100644
--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp
@@ -5,9 +5,11 @@
#include "metadata.hpp"
#include <cstring>
+#include <iterator>
#include <optional>
#include "intel_npu/utils/logger/logger.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "openvino/runtime/shared_buffer.hpp"
namespace intel_npu {
@@ -51,6 +53,10 @@ void OpenvinoVersion::write(std::ostream& stream) {
stream.write(reinterpret_cast<const char*>(&_patch), sizeof(_patch));
}
+size_t OpenvinoVersion::get_openvino_version_size() const {
+ return sizeof(_major) + sizeof(_minor) + sizeof(_patch);
+}
+
MetadataBase::MetadataBase(uint32_t version, uint64_t blobDataSize) : _version(version), _blobDataSize(blobDataSize) {}
Metadata<METADATA_VERSION_2_0>::Metadata(uint64_t blobSize, std::optional<OpenvinoVersion> ovVersion)
@@ -108,7 +114,14 @@ void Metadata<METADATA_VERSION_2_1>::read(const ov::Tensor& tensor) {
}
}
-void MetadataBase::append_blob_size_and_magic(std::ostream& stream) {
+void MetadataBase::append_padding_blob_size_and_magic(std::ostream& stream) {
+ size_t metadataSize = get_metadata_size() + sizeof(_blobDataSize) + MAGIC_BYTES.size();
+ size_t size = utils::align_size_to_standarg_page_size(metadataSize);
+ size_t paddingSize = size - metadataSize;
+ if (paddingSize > 0) {
+ std::fill_n(std::ostream_iterator<char>(stream), paddingSize, 0);
+ }
+
stream.write(reinterpret_cast<const char*>(&_blobDataSize), sizeof(_blobDataSize));
stream.write(MAGIC_BYTES.data(), MAGIC_BYTES.size());
}
@@ -121,14 +134,16 @@ void Metadata<METADATA_VERSION_2_0>::write(std::ostream& stream) {
void Metadata<METADATA_VERSION_2_1>::write(std::ostream& stream) {
Metadata<METADATA_VERSION_2_0>::write(stream);
- uint64_t numberOfInits = _initSizes.has_value() ? _initSizes->size() : 0;
- stream.write(reinterpret_cast<const char*>(&numberOfInits), sizeof(numberOfInits));
+ _numberOfInits = _initSizes.has_value() ? _initSizes->size() : 0;
+ stream.write(reinterpret_cast<const char*>(&_numberOfInits), sizeof(_numberOfInits));
if (_initSizes.has_value()) {
for (uint64_t initSize : _initSizes.value()) {
stream.write(reinterpret_cast<const char*>(&initSize), sizeof(initSize));
}
}
+
+ append_padding_blob_size_and_magic(stream);
}
std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSize) {
@@ -284,4 +299,20 @@ std::optional<std::vector<uint64_t>> Metadata<METADATA_VERSION_2_1>::get_init_si
return _initSizes;
}
+size_t Metadata<METADATA_VERSION_2_0>::get_metadata_size() const {
+ return sizeof(_version) + _ovVersion.get_openvino_version_size();
+}
+
+size_t Metadata<METADATA_VERSION_2_1>::get_metadata_size() const {
+ size_t metadataSize = Metadata<METADATA_VERSION_2_0>::get_metadata_size() + sizeof(_numberOfInits);
+
+ if (_initSizes.has_value()) {
+ for (size_t initSize : _initSizes.value()) {
+ metadataSize += sizeof(initSize);
+ }
+ }
+
+ return metadataSize;
+}
+
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index 1fda16a353b..ffaf292fc66 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -15,6 +15,7 @@
#include "intel_npu/common/itt.hpp"
#include "intel_npu/config/npuw.hpp"
#include "intel_npu/config/options.hpp"
+#include "intel_npu/utils/utils.hpp"
#include "intel_npu/utils/zero/zero_init.hpp"
#include "npuw/compiled_model.hpp"
#include "npuw/llm_compiled_model.hpp"
@@ -689,7 +690,8 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& stream, c
}
blobSize = metadata->get_blob_size();
}
- ov::Tensor tensor(ov::element::u8, ov::Shape{blobSize});
+ ov::Allocator customAllocator{utils::AlignedAllocator{utils::STANDARD_PAGE_SIZE}};
+ ov::Tensor tensor(ov::element::u8, ov::Shape{blobSize}, customAllocator);
if (blobSize > static_cast<decltype(blobSize)>(std::numeric_limits<std::streamsize>::max())) {
OPENVINO_THROW("Blob size is too large to be represented on a std::streamsize!");
}
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp
new file mode 100644
index 00000000000..73ddbeca51e
--- /dev/null
+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/utils.hpp
@@ -0,0 +1,54 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+//
+// Class for pretty-logging.
+//
+
+#pragma once
+
+#include <iostream>
+
+#include "openvino/runtime/allocator.hpp"
+
+namespace intel_npu {
+
+namespace utils {
+
+constexpr std::size_t STANDARD_PAGE_SIZE = 4096;
+
+struct AlignedAllocator {
+public:
+ AlignedAllocator(const size_t align_size) : _align_size(align_size) {}
+
+ void* allocate(const size_t bytes, const size_t /*alignment*/) {
+ return ::operator new(bytes, std::align_val_t(_align_size));
+ }
+
+ void deallocate(void* handle, const size_t /*bytes*/, const size_t /*alignment*/) noexcept {
+ ::operator delete(handle, std::align_val_t(_align_size));
+ }
+
+ bool is_equal(const AlignedAllocator&) const {
+ return true;
+ }
+
+private:
+ const size_t _align_size;
+};
+
+static inline bool memory_and_size_aligned_to_standard_page_size(void* addr, size_t size) {
+ auto addr_int = reinterpret_cast<uintptr_t>(addr);
+
+ // addr is aligned to standard page size
+ return (addr_int % STANDARD_PAGE_SIZE == 0) && (size % STANDARD_PAGE_SIZE == 0);
+}
+
+static inline size_t align_size_to_standarg_page_size(size_t size) {
+ return (size + utils::STANDARD_PAGE_SIZE - 1) & ~(utils::STANDARD_PAGE_SIZE - 1);
+}
+
+} // namespace utils
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp
index d680c456abe..73ecdc818a1 100644
--- a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp
+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp
@@ -6,18 +6,13 @@
#include <ze_api.h>
+#include "intel_npu/utils/utils.hpp"
#include "intel_npu/utils/zero/zero_api.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
#include "openvino/core/type/element_iterator.hpp"
using namespace ov::intel_npu;
-namespace {
-
-constexpr std::size_t STANDARD_PAGE_SIZE = 4096;
-
-} // namespace
-
namespace intel_npu {
ZeroRemoteTensor::ZeroRemoteTensor(const std::shared_ptr<ov::IRemoteContext>& context,
@@ -108,7 +103,6 @@ void ZeroRemoteTensor::update_strides() {
}
const std::string& ZeroRemoteTensor::get_device_name() const {
- OPENVINO_ASSERT(_context != nullptr);
return _context->get_device_name();
}
@@ -152,7 +146,7 @@ bool ZeroRemoteTensor::deallocate() noexcept {
void ZeroRemoteTensor::allocate(const size_t bytes) {
switch (_mem_type) {
case MemType::L0_INTERNAL_BUF: {
- size_t size = (bytes + STANDARD_PAGE_SIZE - 1) & ~(STANDARD_PAGE_SIZE - 1);
+ size_t size = (bytes + utils::STANDARD_PAGE_SIZE - 1) & ~(utils::STANDARD_PAGE_SIZE - 1);
ze_host_mem_alloc_desc_t desc = {};
if (_tensor_type == TensorType::INPUT) {
@@ -163,7 +157,7 @@ void ZeroRemoteTensor::allocate(const size_t bytes) {
}
THROW_ON_FAIL_FOR_LEVELZERO(
"zeMemAllocHost",
- zeMemAllocHost(_init_structs->getContext(), &desc, size, STANDARD_PAGE_SIZE, &_data));
+ zeMemAllocHost(_init_structs->getContext(), &desc, size, utils::STANDARD_PAGE_SIZE, &_data));
break;
}
case MemType::SHARED_BUF: {
@@ -185,7 +179,7 @@ void ZeroRemoteTensor::allocate(const size_t bytes) {
zeMemAllocDevice(_init_structs->getContext(),
&desc,
bytes,
- STANDARD_PAGE_SIZE,
+ utils::STANDARD_PAGE_SIZE,
_init_structs->getDevice(),
&_data));
#else
@@ -198,7 +192,7 @@ void ZeroRemoteTensor::allocate(const size_t bytes) {
ze_host_mem_alloc_desc_t desc = {ZE_STRUCTURE_TYPE_HOST_MEM_ALLOC_DESC, &memory_import, 0};
THROW_ON_FAIL_FOR_LEVELZERO(
"zeMemAllocHost",
- zeMemAllocHost(_init_structs->getContext(), &desc, bytes, STANDARD_PAGE_SIZE, &_data));
+ zeMemAllocHost(_init_structs->getContext(), &desc, bytes, utils::STANDARD_PAGE_SIZE, &_data));
#endif
break;
}
diff --git a/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/import_export.hpp b/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/import_export.hpp
index 722b794e066..32a3aca6c95 100644
--- a/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/import_export.hpp
+++ b/src/plugins/intel_npu/tests/functional/internal/overload/compiled_model/import_export.hpp
@@ -2,6 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <sstream>
+
#include "behavior/compiled_model/import_export.hpp"
#include "common_test_utils/subgraph_builders/conv_pool_relu.hpp"
#include "intel_npu/npu_private_properties.hpp"
@@ -64,6 +66,36 @@ TEST_P(OVCompiledGraphImportExportTestNPU, CanImportModelWithApplicationHeaderAn
}
}
+TEST_P(OVCompiledGraphImportExportTestNPU, CheckSizeOfExportedModelIfMultipleOfPageSize) {
+ ov::Core core;
+ std::stringstream sstream;
+
+ auto model = ov::test::utils::make_conv_pool_relu();
+ core.compile_model(model, target_device, configuration).export_model(sstream);
+
+ std::size_t size = sstream.str().size();
+
+ ASSERT_TRUE(size != 0) << "Size of the exported model shall be different from 0";
+ ASSERT_TRUE(size % 4096 == 0) << "Size of the exported model shall be multiple of 4096";
+}
+
+TEST_P(OVCompiledGraphImportExportTestNPU, CheckSizeOfBlobIfMultipleOfPageSize) {
+ ov::Core core;
+ std::stringstream sstream;
+
+ auto model = ov::test::utils::make_conv_pool_relu();
+ core.compile_model(model, target_device, configuration).export_model(sstream);
+
+ uint64_t size_of_blob;
+ std::size_t size = sstream.str().size();
+
+ sstream.seekg(size - std::streampos(5) /*MAGIC_BYTES*/ - sizeof(size_of_blob), std::ios::cur);
+ sstream.read(reinterpret_cast<char*>(&size_of_blob), sizeof(size_of_blob));
+
+ ASSERT_TRUE(size_of_blob != 0) << "Size of the blob shall be different from 0";
+ ASSERT_TRUE(size_of_blob % 4096 == 0) << "Size of the blob shall be multiple of 4096";
+}
+
} // namespace behavior
} // namespace test
diff --git a/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp b/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp
index e44b2dca278..c2742c31155 100644
--- a/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp
+++ b/src/plugins/intel_npu/tests/unit/npu/metadata_version.cpp
@@ -40,7 +40,6 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlob) {
auto meta = MetadataTest(blobSize, CURRENT_OPENVINO_VERSION);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
std::unique_ptr<MetadataBase> storedMeta;
OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
@@ -61,7 +60,6 @@ TEST_F(MetadataUnitTests, writeAndReadInvalidOpenvinoVersion) {
auto meta = MetadataTest(blobSize, wrongOvVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
std::unique_ptr<MetadataBase> storedMeta;
OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
@@ -84,7 +82,6 @@ TEST_F(MetadataUnitTests, writeAndReadInvalidMetadataVersion) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
ASSERT_ANY_THROW(auto storedMeta = read_metadata_from(stream));
stream.seekg(0, std::ios::beg);
@@ -104,7 +101,6 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerMinorVersion) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
std::unique_ptr<MetadataBase> storedMeta;
OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));
storedMeta->is_compatible();
@@ -166,7 +162,6 @@ TEST_P(MetadataVersionTestFixture, writeAndReadInvalidMetadataVersion) {
}
const std::vector badMetadataVersions = {
- MetadataBase::make_version(CURRENT_METADATA_MAJOR_VERSION, CURRENT_METADATA_MINOR_VERSION - 1),
MetadataBase::make_version(CURRENT_METADATA_MAJOR_VERSION + 1, CURRENT_METADATA_MINOR_VERSION),
MetadataBase::make_version(CURRENT_METADATA_MAJOR_VERSION + 1, CURRENT_METADATA_MINOR_VERSION + 1),
MetadataBase::make_version(CURRENT_METADATA_MAJOR_VERSION + 1, CURRENT_METADATA_MINOR_VERSION - 1),
@@ -190,7 +185,6 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtEnd) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
// inserting a new field at the end of the blob, between last metadata field and blobDataSize
std::string temp = stream.str();
@@ -222,7 +216,6 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtMiddle) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
// inserting a new field at the middle of the blob, between metadata version and OV version size
std::string temp = stream.str();
@@ -252,7 +245,6 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithRemovedField) {
meta.set_version(dummyVersion);
OV_ASSERT_NO_THROW(meta.write(stream));
- OV_ASSERT_NO_THROW(meta.append_blob_size_and_magic(stream));
// removing fields between metadata version and blob data size
std::string temp = stream.str();
diff --git a/src/plugins/intel_npu/thirdparty/level-zero-ext b/src/plugins/intel_npu/thirdparty/level-zero-ext
index e89a57dd5d0..f8bba8915e0 160000
--- a/src/plugins/intel_npu/thirdparty/level-zero-ext
+++ b/src/plugins/intel_npu/thirdparty/level-zero-ext
@@ -1 +1 @@
-Subproject commit e89a57dd5d082a94162fea649f039a0775675cda
+Subproject commit f8bba8915e0a5fe8317f7aa48007ecc5a8c179ca