Skip to content

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

[NPU] Create NPU executor class (#36013)

Bogdan Pereanueac4b447df25
diff --git a/src/plugins/intel_npu/README.md b/src/plugins/intel_npu/README.md
index f4c3fa62bc5..c910aad6a0b 100644
--- a/src/plugins/intel_npu/README.md
+++ b/src/plugins/intel_npu/README.md
@@ -190,7 +190,7 @@ The following properties are supported (may differ based on current system confi
| `ov::supported_properties`/</br>`SUPPORTED_METRICS`/</br>`SUPPORTED_CONFIG_KEYS` | RO | Returns a list of all supported properties.</br> Can be queried on runtime. | `N/A` | `N/A` |
| `ov::caching_properties`/</br>`CACHING_PROPERTIES` | RW | Returns a list of all properties that are used by OpenVINO cache to build the hash key. | `N/A` | `N/A` |
| `ov::compilation_num_threads`/</br>`COMPILATION_NUM_THREADS` | RW | Maximum number of threads that can be used for compilation tasks. | `N/A` | `N/A` |
-| `ov::num_streams`/</br>`NUM_STREAMS` | RO | Not used by the NPU plugin.</br> Always set to 1. | `AUTO/`</br>`INT` | `1` |
+| `ov::num_streams`/</br>`NUM_STREAMS` | RW | Sets the per-executor stream/thread limit. Executor layout depends on mode: `AUTO` uses only the task executor; `0` runs `start_async` on the caller thread, uses a single wait executor thread, and disables the callback executor; explicit positive values use separate executors for start, wait, and callback stages, each configured with `num_streams` threads. | `AUTO/`</br>`INT` | `AUTO` |
| `ov::optimal_number_of_infer_requests`/</br>`OPTIMAL_NUMBER_OF_INFER_REQUESTS` | RO | Returns the optimal number of inference requests to be used by the application. Depends on the platform version and on ov::hint::performance_mode. Please see the table below. | `N/A` | `N/A` |
| `ov::range_for_async_infer_requests`/</br>`RANGE_FOR_ASYNC_INFER_REQUESTS` | RO | Returns a tuple (bottom, top, step). </br> Not used by the NPU plugin. | `N/A` | `N/A` |
| `ov::range_for_streams`/</br>`RANGE_FOR_STREAMS` | RO | Returns a tuple (bottom, top).</br> Not used by the NPU plugin. | `N/A`| `N/A` |
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp
index 882e2b5c9c6..334251bb08e 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/options.hpp
@@ -645,32 +645,30 @@ struct NUM_STREAMS final : OptionBase<NUM_STREAMS, ov::streams::Num> {
return "ov::streams::Num";
}
- // The only supported number for currently supported platforms.
- // FIXME: update in the future
static ov::streams::Num defaultValue() {
- return ov::streams::Num(1);
+ return ov::streams::AUTO;
}
static ov::streams::Num parse(std::string_view val) {
std::istringstream stringStream = std::istringstream(std::string(val));
ov::streams::Num numberOfStreams;
-
stringStream >> numberOfStreams;
return numberOfStreams;
}
- static std::string itoString(const ov::streams::Num& val) {
+ static std::string toString(const ov::streams::Num& val) {
std::ostringstream stringStream;
-
stringStream << val;
return stringStream.str();
}
static void validateValue(const ov::streams::Num& num) {
- if (defaultValue() != num && ov::streams::AUTO != num) {
- OPENVINO_THROW("NUM_STREAMS can not be set");
+ if (num != ov::streams::AUTO && num < 0) {
+ OPENVINO_THROW("NUM_STREAMS cannot be set to this value: ",
+ num,
+ ". Supported values are non-negative integers (including 0) or ov::streams::AUTO");
}
}
@@ -683,7 +681,7 @@ struct NUM_STREAMS final : OptionBase<NUM_STREAMS, ov::streams::Num> {
}
static ov::PropertyMutability mutability() {
- return ov::PropertyMutability::RO;
+ return ov::PropertyMutability::RW;
}
};
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 9f6fcfcddf2..a2cbd8feedc 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
@@ -24,6 +24,18 @@ std::string getCompilationPlatform(const std::string_view platform,
* @brief Gets the device by its ID.
*/
std::shared_ptr<IDevice> getDeviceById(const ov::SoPtr<IEngineBackend>& engineBackend, const std::string& deviceId);
+
+/**
+ * @brief Gets the optimal number of infer requests in parallel for the given platform and performance mode.
+ * @param platform The platform for which to get the optimal number of infer requests.
+ * @param performanceMode The performance mode for which to get the optimal number of infer requests.
+ * @return The optimal number of infer requests in parallel.
+ * @note This is the value provided by the plugin, application should query and consider it, but may supply its own
+ * preference for number of parallel requests via dedicated configuration
+ */
+uint32_t getOptimalNumberOfInferRequestsInParallel(std::string_view platform,
+ const ov::hint::PerformanceMode performanceMode);
+
} // namespace utils
} // namespace intel_npu
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 fbd0375d5de..d98905ed525 100644
--- a/src/plugins/intel_npu/src/common/src/device_helpers.cpp
+++ b/src/plugins/intel_npu/src/common/src/device_helpers.cpp
@@ -71,4 +71,13 @@ std::shared_ptr<IDevice> utils::getDeviceById(const ov::SoPtr<IEngineBackend>& e
return nullptr;
}
+uint32_t utils::getOptimalNumberOfInferRequestsInParallel(std::string_view platform,
+ const ov::hint::PerformanceMode performanceMode) {
+ if (performanceMode != ov::hint::PerformanceMode::THROUGHPUT) {
+ return 1;
+ }
+
+ return (platform == ov::intel_npu::Platform::NPU3720) ? 4 : 8;
+}
+
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp b/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp
index c999c336e17..3a590fbe5a8 100644
--- a/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/async_infer_request.hpp
@@ -16,7 +16,7 @@ class AsyncInferRequest final : public ov::IAsyncInferRequest {
public:
explicit AsyncInferRequest(const std::shared_ptr<InferRequest>& inferRequest,
const std::shared_ptr<ov::threading::ITaskExecutor>& requestExecutor,
- const std::shared_ptr<ov::threading::ITaskExecutor>& getResultExecutor,
+ const std::shared_ptr<ov::threading::ITaskExecutor>& resultExecutor,
const std::shared_ptr<ov::threading::ITaskExecutor>& callbackExecutor);
AsyncInferRequest(const AsyncInferRequest&) = delete;
@@ -25,13 +25,9 @@ public:
~AsyncInferRequest();
- std::shared_ptr<InferRequest> get_sync_infer_request() {
- return _syncInferRequest;
- }
-
private:
- std::shared_ptr<InferRequest> _syncInferRequest;
- std::shared_ptr<ov::threading::ITaskExecutor> _getResultExecutor;
+ std::shared_ptr<InferRequest> _inferRequest;
+ std::shared_ptr<ov::threading::ITaskExecutor> _resultExecutor;
};
} // namespace intel_npu
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 cb3f3173c19..62e5c06d5af 100644
--- a/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/compiled_model.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include <mutex>
#include <optional>
#include "intel_npu/common/icompiled_model.hpp"
@@ -25,9 +26,8 @@ public:
* @param plugin Pointer towards the NPU plugin instance
* @param device Backend specific object through which inference requests can be created
* @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
+ * @param batchSize Optional batch size value.
*/
CompiledModel(const std::shared_ptr<const ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
@@ -40,7 +40,7 @@ public:
CompiledModel& operator=(const CompiledModel&) = delete;
- ~CompiledModel() override;
+ ~CompiledModel() override = default;
std::shared_ptr<ov::IAsyncInferRequest> create_infer_request() const override;
@@ -61,16 +61,18 @@ public:
void release_memory() override;
private:
+ // For special config, stream executors must be set accordingly to ensure correct behavior.
void configure_stream_executors();
Logger _logger;
- const std::shared_ptr<IDevice> _device;
- std::shared_ptr<ov::threading::ITaskExecutor> _resultExecutor;
+ const std::shared_ptr<IDevice> _device;
std::unique_ptr<Properties> _propertiesManager;
-
std::shared_ptr<IGraph> _graph;
+ std::shared_ptr<ov::threading::ITaskExecutor> _resultExecutor = nullptr;
+ mutable std::once_flag _streamExecutorsInitFlag;
+
std::optional<int64_t> _batchSize;
};
diff --git a/src/plugins/intel_npu/src/plugin/include/executor.hpp b/src/plugins/intel_npu/src/plugin/include/executor.hpp
new file mode 100644
index 00000000000..3124afa75b1
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/include/executor.hpp
@@ -0,0 +1,30 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <chrono>
+#include <memory>
+#include <string_view>
+
+#include "openvino/runtime/threading/itask_executor.hpp"
+
+namespace intel_npu {
+
+/**
+ * @brief Creates a task executor with fixed-size or adaptive worker behavior.
+ *
+ * @param name Base thread name prefix used for worker threads.
+ * @param workers Baseline number of workers to keep active.
+ * @param allowWorkerGrowth If true, allows creating additional workers on demand.
+ * @param idleTimeout Idle timeout after which extra adaptive workers can stop.
+ * @return Shared pointer to the created task executor.
+ */
+std::shared_ptr<ov::threading::ITaskExecutor> make_executor(
+ std::string_view name,
+ size_t workers,
+ bool allowWorkerGrowth = false,
+ std::chrono::milliseconds idleTimeout = std::chrono::milliseconds{30'000});
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/include/metrics.hpp b/src/plugins/intel_npu/src/plugin/include/metrics.hpp
index dae6f6c85db..61a784deca8 100644
--- a/src/plugins/intel_npu/src/plugin/include/metrics.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/metrics.hpp
@@ -48,6 +48,7 @@ private:
const ov::SoPtr<IEngineBackend> _backend;
std::vector<std::string> _supportedMetrics;
std::vector<std::string> _supportedConfigKeys;
+ static constexpr uint32_t _maxNumOfOptimalInferRequests = 8u;
const std::vector<std::string> _optimizationCapabilities = {
ov::device::capability::FP16,
ov::device::capability::INT8,
@@ -55,10 +56,10 @@ private:
};
// Metric to provide a hint for a range for number of async infer requests. (bottom bound, upper bound, step)
- const std::tuple<uint32_t, uint32_t, uint32_t> _rangeForAsyncInferRequests{1u, 10u, 1u};
+ const std::tuple<uint32_t, uint32_t, uint32_t> _rangeForAsyncInferRequests{1u, _maxNumOfOptimalInferRequests, 1u};
// Metric to provide information about a range for streams.(bottom bound, upper bound)
- const std::tuple<uint32_t, uint32_t> _rangeForStreams{1u, 4u};
+ const std::tuple<uint32_t, uint32_t> _rangeForStreams{0u, _maxNumOfOptimalInferRequests};
std::string getDeviceName(const std::string& specifiedDeviceName) const;
std::shared_ptr<intel_npu::IDevice> getDevice(const std::string& specifiedDeviceName) const;
diff --git a/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp b/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp
index 622e5a51f1a..8b3abc96c5b 100644
--- a/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/async_infer_request.cpp
@@ -8,19 +8,23 @@
namespace intel_npu {
-// clang-format off
-AsyncInferRequest::AsyncInferRequest(const std::shared_ptr<InferRequest>& syncInferRequest,
+AsyncInferRequest::AsyncInferRequest(const std::shared_ptr<InferRequest>& inferRequest,
const std::shared_ptr<ov::threading::ITaskExecutor>& requestExecutor,
- const std::shared_ptr<ov::threading::ITaskExecutor>& getResultExecutor,
+ const std::shared_ptr<ov::threading::ITaskExecutor>& resultExecutor,
const std::shared_ptr<ov::threading::ITaskExecutor>& callbackExecutor)
- : ov::IAsyncInferRequest(syncInferRequest, requestExecutor, callbackExecutor),
- _syncInferRequest(syncInferRequest), _getResultExecutor(getResultExecutor) {
- m_pipeline = {
- {requestExecutor, [this] { _syncInferRequest->infer_async(); }},
- {getResultExecutor, [this] { _syncInferRequest->get_result(); }}
- };
+ : ov::IAsyncInferRequest(inferRequest, requestExecutor, callbackExecutor),
+ _inferRequest(inferRequest),
+ _resultExecutor(resultExecutor) {
+ if (_resultExecutor) {
+ m_pipeline = {{requestExecutor,
+ [this] {
+ _inferRequest->infer_async();
+ }},
+ {_resultExecutor, [this] {
+ _inferRequest->get_result();
+ }}};
+ }
}
-// clang-format on
AsyncInferRequest::~AsyncInferRequest() {
stop_and_wait();
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 6a1d31149a9..02066a470c6 100644
--- a/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/compiled_model.cpp
@@ -9,6 +9,8 @@
#include <string_view>
#include "async_infer_request.hpp"
+#include "executor.hpp"
+#include "intel_npu/common/device_helpers.hpp"
#include "intel_npu/common/itt.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/options.hpp"
@@ -16,21 +18,17 @@
#include "metadata.hpp"
#include "openvino/pass/constant_folding.hpp"
#include "openvino/runtime/properties.hpp"
-#include "openvino/runtime/system_conf.hpp"
-#include "openvino/runtime/threading/executor_manager.hpp"
#include "transformations/utils/utils.hpp"
namespace intel_npu {
-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 std::shared_ptr<IGraph>& graph,
const FilteredConfig& config,
const std::optional<int64_t>& batchSize)
- : ICompiledModel(model, plugin),
+ : ICompiledModel(model, plugin, nullptr, nullptr),
_logger("CompiledModel", config.get<LOG_LEVEL>()),
_device(device),
_graph(graph),
@@ -48,19 +46,16 @@ CompiledModel::CompiledModel(const std::shared_ptr<const ov::Model>& model,
OV_ITT_TASK_CHAIN(COMPILED_MODEL, itt::domains::NPUPlugin, "CompiledModel::CompiledModel", "initialize_properties");
_propertiesManager = std::make_unique<Properties>(PropertiesType::COMPILED_MODEL, localConfig);
- configure_stream_executors();
-
OV_ITT_TASK_SKIP(COMPILED_MODEL);
}
-CompiledModel::~CompiledModel() {
- _logger.debug("~CompiledModel()");
- std::dynamic_pointer_cast<ov::threading::IStreamsExecutor>(get_task_executor())->cpu_reset();
-}
-
std::shared_ptr<ov::IAsyncInferRequest> CompiledModel::create_infer_request() const {
OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "CompiledModel::create_infer_request");
+ std::call_once(_streamExecutorsInitFlag, [this] {
+ const_cast<CompiledModel*>(this)->configure_stream_executors();
+ });
+
// sanity check
OPENVINO_ASSERT(_device != nullptr, "No available devices. Failed to create infer request!");
@@ -74,10 +69,10 @@ std::shared_ptr<ov::IAsyncInferRequest> CompiledModel::create_infer_request() co
"Graph is unavailable or failed to initialize. The driver may be missing or too old to run "
"inference for this blob.");
- const std::shared_ptr<InferRequest>& syncInferRequest =
+ const std::shared_ptr<InferRequest>& inferRequest =
_device->createInferRequest(shared_from_this(), _propertiesManager->getConfig());
- return std::make_shared<AsyncInferRequest>(syncInferRequest,
+ return std::make_shared<AsyncInferRequest>(inferRequest,
get_task_executor(),
_resultExecutor,
get_callback_executor());
@@ -276,12 +271,43 @@ void CompiledModel::release_memory() {
}
void CompiledModel::configure_stream_executors() {
- std::shared_ptr<ov::threading::ITaskExecutor> task_executor = std::make_shared<ov::threading::CPUStreamsExecutor>(
- ov::threading::IStreamsExecutor::Config{"NPUPlugin executor"});
+ const FilteredConfig& config = get_config();
- set_task_executor(std::move(task_executor));
- const auto executorId = _graph->get_metadata().name + "_NPUResultExecutor";
- _resultExecutor = ov::threading::executor_manager()->get_executor(executorId);
+ // In case of sequential execution of async requests for the same compiled model, the compiled model must use
+ // dedicated executors with a single thread to ensure sequential execution of its async requests.
+ if (config.get<RUN_INFERENCES_SEQUENTIALLY>()) {
+ set_task_executor(make_executor("Intel NPU plugin start inferences executor", 1));
+ _resultExecutor = make_executor("Intel NPU plugin wait inferences executor", 1);
+
+ return;
+ }
+
+ const auto numStreams = config.get<NUM_STREAMS>();
+ if (numStreams > 0) {
+ // Use a single thread for start executors to reduce contention on the shared task queue, while scaling wait
+ // executor workers with num_streams to improve result fetch throughput. Callbacks intentionally run on wait
+ // threads.
+ const size_t workers = static_cast<size_t>(numStreams);
+
+ set_task_executor(make_executor("Intel NPU plugin start inferences executor", 1));
+ _resultExecutor = make_executor("Intel NPU plugin wait inferences executor", workers);
+ } else if (numStreams == 0) {
+ // For special case when num_streams is explicitly set to 0, start inference will happen in the same thread as
+ // the call to InferRequest::start_async, while wait executor will still be created with a single worker.
+ // Callback execution is intentionally done on that wait thread.
+ set_task_executor(make_executor("Intel NPU plugin start inferences executor", 0));
+ _resultExecutor = make_executor("Intel NPU plugin wait inferences executor", 1);
+ } else {
+ // Auto mode (default): workers are created on demand. The baseline number of workers that stay alive during
+ // idle periods (30 s timeout) is derived from the optimal number of parallel infer requests recommended for
+ // the current platform in THROUGHPUT mode. The pool can then grow dynamically to match runtime workload.
+ const size_t keepWorkers = static_cast<size_t>(
+ utils::getOptimalNumberOfInferRequestsInParallel(config.get<PLATFORM>(),
+ ov::hint::PerformanceMode::THROUGHPUT));
+
+ set_task_executor(make_executor("Intel NPU plugin run inferences executor", keepWorkers, true));
+ _resultExecutor = nullptr;
+ }
}
} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/src/executor.cpp b/src/plugins/intel_npu/src/plugin/src/executor.cpp
new file mode 100644
index 00000000000..626e90cfc3d
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/src/executor.cpp
@@ -0,0 +1,234 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "executor.hpp"
+
+#include <condition_variable>
+#include <mutex>
+#include <queue>
+#include <thread>
+#include <utility>
+#include <vector>
+
+#include "intel_npu/common/itt.hpp"
+
+namespace intel_npu {
+
+namespace {
+
+/**
+ * @brief Task executor with adaptive worker growth for NPU plugin jobs.
+ *
+ * The executor processes tasks submitted through `run()` using an internal queue
+ * and a set of worker threads.
+ *
+ * Behavior depends on constructor parameters:
+ * - Fixed-size mode (`allowWorkerGrowth == false`): starts exactly `workers`
+ * threads during construction.
+ * - Adaptive mode (`allowWorkerGrowth == true`): starts with one worker and
+ * grows the pool when queued load exceeds active workers.
+ *
+ * In adaptive mode, workers above the baseline (`workers`) can terminate after
+ * `idleTimeout` if no work arrives, reducing idle thread usage.
+ *
+ * The destructor performs a graceful shutdown by signaling stop, waking workers,
+ * and joining all owned threads.
+ */
+class AdaptiveThreadExecutor final : public ov::threading::ITaskExecutor {
+public:
+ AdaptiveThreadExecutor(std::string_view name,
+ size_t workers,
+ bool allowWorkerGrowth,
+ std::chrono::milliseconds idleTimeout)
+ : _name(name),
+ _workersBaseline(workers),
+ _allowWorkerGrowth(allowWorkerGrowth),
+ _idleTimeout(idleTimeout) {
+ std::lock_guard<std::mutex> lock(_mutex);
+
+ if (_allowWorkerGrowth) {
+ start_worker_locked();
+ return;
+ }
+
+ while (_activeWorkers < _workersBaseline) {
+ start_worker_locked();
+ }
+ }
+
+ ~AdaptiveThreadExecutor() override {
+ {
+ std::lock_guard<std::mutex> lock(_mutex);
+ _stopped = true;
+ }
+ _condition.notify_all();
+ for (auto& worker : _workers) {
+ if (worker.thread.joinable()) {
+ worker.thread.join();
+ }
+ }
+ }
+
+ void run(ov::threading::Task task) override {
+ reap_finished_workers();
+
+ if (_workersBaseline == 0 && !_allowWorkerGrowth) {
+ try {
+ task();
+ } catch (...) {
+ }
+ return;
+ }
+
+ {
+ std::lock_guard<std::mutex> lock(_mutex);
+ _tasks.push(TaskEntry{std::move(task)});
+
+ if (_allowWorkerGrowth) {
+ while ((_tasks.size() + _busyWorkers) > _activeWorkers) {
+ start_worker_locked();
+ }
+ }
+ }
+ _condition.notify_one();
+ }
+
+private:
+ struct TaskEntry {
+ ov::threading::Task task;
+ };
+
+ struct WorkerEntry {
+ std::thread thread;
+ bool finished = false;
+ };
+
+ void reap_finished_workers() {
+ std::vector<std::thread> threadsToJoin;
+ std::vector<size_t> joinedIndices;
+
+ {
+ std::lock_guard<std::mutex> lock(_mutex);
+ for (const auto index : _retiredWorkerIndices) {
+ if (_workers[index].finished && _workers[index].thread.joinable()) {
+ threadsToJoin.emplace_back(std::move(_workers[index].thread));
+ joinedIndices.emplace_back(index);
+ }
+ }
+ _retiredWorkerIndices.clear();
+ }
+
+ for (auto& thread : threadsToJoin) {
+ thread.join();
+ }
+
+ if (!joinedIndices.empty()) {
+ std::lock_guard<std::mutex> lock(_mutex);
+ for (const auto index : joinedIndices) {
+ _workers[index].finished = false;
+ _freeWorkerIndices.emplace_back(index);
+ }
+ }
+ }
+
+ void start_worker_locked() {
+ const size_t workerId = _nextWorkerId++;
+ size_t workerIndex = 0;
+ const bool reuseSlot = !_freeWorkerIndices.empty();
+ if (!_freeWorkerIndices.empty()) {
+ workerIndex = _freeWorkerIndices.back();
+ _freeWorkerIndices.pop_back();
+ } else {
+ workerIndex = _workers.size();
+ _workers.emplace_back();
+ }
+
+ try {
+ std::thread workerThread([this, workerId, workerIndex] {
+ openvino::itt::threadName(_name + "_" + std::to_string(workerId));
+ for (;;) {
+ ov::threading::Task task;
+ {
+ std::unique_lock<std::mutex> lock(_mutex);
+ while (!_stopped && _tasks.empty()) {
+ if (_activeWorkers > _workersBaseline) {
+ if (!_condition.wait_for(lock, _idleTimeout, [&] {
+ return _stopped || !_tasks.empty();
+ })) {
+ if (_activeWorkers > _workersBaseline) {
+ --_activeWorkers;
+ _workers[workerIndex].finished = true;
+ _retiredWorkerIndices.emplace_back(workerIndex);
+ return;
+ }
+
+ continue;
+ }
+ } else {
+ _condition.wait(lock, [&] {
+ return _stopped || !_tasks.empty();
+ });
+ }
+ }
+
+ if (_stopped && _tasks.empty()) {
+ --_activeWorkers;
+ _workers[workerIndex].finished = true;
+ _retiredWorkerIndices.emplace_back(workerIndex);
+ return;
+ }
+
+ task = std::move(_tasks.front().task);
+ _tasks.pop();
+ ++_busyWorkers;
+ }
+
+ task();
+
+ {
+ std::lock_guard<std::mutex> lock(_mutex);
+ --_busyWorkers;
+ }
+ }
+ });
+
+ _workers[workerIndex].thread = std::move(workerThread);
+ _workers[workerIndex].finished = false;
+ ++_activeWorkers;
+ } catch (...) {
+ if (reuseSlot) {
+ _freeWorkerIndices.emplace_back(workerIndex);
+ } else {
+ _workers.pop_back();
+ }
+ throw;
+ }
+ }
+
+ const std::string _name;
+ const size_t _workersBaseline;
+ const bool _allowWorkerGrowth;
+ const std::chrono::milliseconds _idleTimeout;
+ std::mutex _mutex;
+ std::condition_variable _condition;
+ std::queue<TaskEntry> _tasks;
+ std::vector<WorkerEntry> _workers;
+ std::vector<size_t> _retiredWorkerIndices;
+ std::vector<size_t> _freeWorkerIndices;
+ size_t _nextWorkerId = 0;
+ size_t _activeWorkers = 0;
+ size_t _busyWorkers = 0;
+ bool _stopped = false;
+};
+
+} // namespace
+
+std::shared_ptr<ov::threading::ITaskExecutor> make_executor(std::string_view name,
+ size_t workers,
+ bool allowWorkerGrowth,
+ std::chrono::milliseconds idleTimeout) {
+ return std::make_shared<AdaptiveThreadExecutor>(name, workers, allowWorkerGrowth, idleTimeout);
+}
+
+} // namespace intel_npu
diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cpp
index c971685c747..5ad6e30966d 100644
--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp
@@ -133,6 +133,14 @@ void disableCompilerProperties(intel_npu::FilteredConfig& config, const ov::SoPt
}
}
+// Helper function for retrieving the device name
+std::string get_specified_device_name(const intel_npu::Config& config) {
+ if (config.has<intel_npu::DEVICE_ID>()) {
+ return config.get<intel_npu::DEVICE_ID>();
+ }
+ return std::string();
+}
+
} // namespace
namespace intel_npu {
@@ -403,41 +411,6 @@ namespace intel_npu {
std::make_tuple(PROP_VISIBILITY, ov::PropertyMutability::RO, PROP_RETFUNC)); \
} while (0)
-// Local helper function for appending platform name to the config
-static Config add_platform_to_the_config(Config config, const std::string_view platform) {
- config.update({{ov::intel_npu::platform.name(), std::string(platform)}});
- return config;
-}
-
-// Local helper function for retrieving the device name
-static auto get_specified_device_name(const Config config) {
- if (config.has<DEVICE_ID>()) {
- return config.get<DEVICE_ID>();
- }
- return std::string();
-}
-
-// Heuristically obtained number. Varies depending on the values of PLATFORM and PERFORMANCE_HINT
-// Note: this is the value provided by the plugin, application should query and consider it, but may supply its own
-// preference for number of parallel requests via dedicated configuration
-static int64_t getOptimalNumberOfInferRequestsInParallel(const Config& config) {
- const std::string platform = config.get<PLATFORM>();
-
- if (platform == ov::intel_npu::Platform::NPU3720) {
- if (config.get<PERFORMANCE_HINT>() == ov::hint::PerformanceMode::THROUGHPUT) {
- return 4;
- } else {
- return 1;
- }
- } else {
- if (config.get<PERFORMANCE_HINT>() == ov::hint::PerformanceMode::THROUGHPUT) {
- return 8;
- } else {
- return 1;
- }
- }
-}
-
Properties::Properties(const PropertiesType pType,
const FilteredConfig& config,
const std::shared_ptr<Metrics>& metrics,
@@ -638,16 +611,15 @@ void Properties::registerPluginProperties() {
if (_metrics != nullptr) {
REGISTER_SIMPLE_METRIC(ov::available_devices, true, _metrics->GetAvailableDevicesNames());
REGISTER_SIMPLE_METRIC(ov::device::capabilities, true, _metrics->GetOptimizationCapabilities());
- REGISTER_SIMPLE_METRIC(
- ov::optimal_number_of_infer_requests,
- true,
- static_cast<uint32_t>(getOptimalNumberOfInferRequestsInParallel(add_platform_to_the_config(
- config,
- utils::getCompilationPlatform(
- config.get<PLATFORM>(),
- _backend == nullptr ? config.get<DEVICE_ID>()
- : _backend->getDevice(config.get<DEVICE_ID>())->getName(),
- _backend == nullptr ? std::vector<std::string>() : _backend->getDeviceNames())))));
+ REGISTER_SIMPLE_METRIC(ov::optimal_number_of_infer_requests,
+ true,
+ utils::getOptimalNumberOfInferRequestsInParallel(
+ utils::getCompilationPlatform(
+ config.get<PLATFORM>(),
+ _backend == nullptr ? config.get<DEVICE_ID>()
+ : _backend->getDevice(config.get<DEVICE_ID>())->getName(),
+ _backend == nullptr ? std::vector<std::string>() : _backend->getDeviceNames()),
+ config.get<PERFORMANCE_HINT>()));
REGISTER_SIMPLE_METRIC(ov::range_for_async_infer_requests, true, _metrics->GetRangeForAsyncInferRequest());
REGISTER_SIMPLE_METRIC(ov::range_for_streams, true, _metrics->GetRangeForStreams());
REGISTER_SIMPLE_METRIC(ov::device::pci_info, true, _metrics->GetPciInfo(get_specified_device_name(config)));
@@ -758,6 +730,7 @@ void Properties::registerCompiledModelProperties() {
TRY_REGISTER_SIMPLE_PROPERTY(ov::cache_mode, CACHE_MODE);
// Properties we shall only enable if they were set prior-to-compilation
+ TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::num_streams, NUM_STREAMS);
TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::intel_npu::compiler_type, COMPILER_TYPE);
TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::intel_npu::compiler_version, COMPILER_VERSION);
TRY_REGISTER_COMPILEDMODEL_PROPERTY_IFSET(ov::weights_path, WEIGHTS_PATH);
@@ -847,9 +820,10 @@ void Properties::registerCompiledModelProperties() {
// this implementation here serves only to publish it in supported_properties
return std::string("invalid");
});
- REGISTER_SIMPLE_METRIC(ov::optimal_number_of_infer_requests,
- true,
- static_cast<uint32_t>(getOptimalNumberOfInferRequestsInParallel(config)));
+ REGISTER_SIMPLE_METRIC(
+ ov::optimal_number_of_infer_requests,
+ true,
+ utils::getOptimalNumberOfInferRequestsInParallel(config.get<PLATFORM>(), config.get<PERFORMANCE_HINT>()));
REGISTER_CUSTOM_METRIC(ov::execution_devices, true, [](const Config&) {
// TODO: log an error here as the code shouldn't have gotten here
// this property is implemented in compiled model directly
diff --git a/src/plugins/intel_npu/tests/functional/CMakeLists.txt b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
index 0ebe3f7e5dd..9341a4e5bcf 100644
--- a/src/plugins/intel_npu/tests/functional/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/functional/CMakeLists.txt
@@ -50,6 +50,7 @@ ov_add_test_target(
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/transformations.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/properties.cpp"
"${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/metrics.cpp"
+ "${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/executor.cpp"
LINK_LIBRARIES
${OPTIONAL_FUNC_TESTS_LIBS}
openvino::func_test_utils
diff --git a/src/plugins/intel_npu/tests/functional/behavior/compiled_model/property.cpp b/src/plugins/intel_npu/tests/functional/behavior/compiled_model/property.cpp
index 5de66e274c5..3734e18a68f 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/compiled_model/property.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/compiled_model/property.cpp
@@ -56,7 +56,6 @@ std::vector<std::pair<std::string, ov::Any>> plugin_internal_mutable_properties
std::vector<std::pair<std::string, ov::Any>> plugin_public_immutable_properties = {
{ov::device::uuid.name(), ov::Any("deadbeef")},
{ov::supported_properties.name(), {ov::device::full_name.name()}},
- {ov::num_streams.name(), ov::Any(ov::streams::Num(4))},
{ov::available_devices.name(), ov::Any(std::vector<std::string>{"deadbeef"})},
{ov::device::capabilities.name(), ov::Any(std::vector<std::string>{"deadbeef"})},
{ov::range_for_async_infer_requests.name(),
diff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp
index 6b6c89593be..8386c0b3c07 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.cpp
@@ -12,6 +12,7 @@ using namespace ov::test::behavior;
namespace {
const std::vector<ov::AnyMap> configsInferRequestRunTests = {{}};
+
const std::vector<ov::AnyMap> configsBooleanPrecisionInferRequestRunTests = {
{{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::PLUGIN),
ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::PLUGIN),
@@ -28,12 +29,22 @@ const std::vector<ov::AnyMap> configsBooleanPrecisionInferRequestRunTests = {
{{ov::intel_npu::compiler_type(ov::intel_npu::CompilerType::DRIVER),
ov::intel_npu::batch_mode(ov::intel_npu::BatchMode::COMPILER)}}};
+const std::vector<ov::AnyMap> configsWithDifferentNumStreamsTest = {{{ov::num_streams(0)}},
+ {{ov::num_streams(2)}},
+ {{ov::num_streams(8)}}};
+
INSTANTIATE_TEST_SUITE_P(compatibility_smoke_BehaviorTest,
InferRequestRunTests,
::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),
::testing::ValuesIn(configsInferRequestRunTests)),
InferRequestRunTests::getTestCaseName);
+INSTANTIATE_TEST_SUITE_P(compatibility_smoke_BehaviorTest,
+ NumStreamsTests,
+ ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),
+ ::testing::ValuesIn(configsWithDifferentNumStreamsTest)),
+ InferRequestRunTests::getTestCaseName);
+
INSTANTIATE_TEST_SUITE_P(compatibility_smoke_BehaviorTest,
BooleanPrecisionInferRequestRunTests,
::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),
diff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp
index d4b2b507d64..10ba7a2180a 100644
--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp
+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/infer_request_run.hpp
@@ -959,7 +959,7 @@ TEST_P(RunSeqTests, CheckMultipleRunsSeq0) {
for (uint32_t i = 0; i < inferences; i++) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1019,7 +1019,7 @@ TEST_P(RunSeqTests, CheckMultipleRunsSeq1) {
for (int i = inferences - 1; i >= 0; i--) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1176,7 +1176,7 @@ TEST_P(RunSeqTests, CheckMultipleRunsSeq4) {
for (int i = inferences - 1; i >= 0; i--) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1202,7 +1202,7 @@ TEST_P(RunSeqTests, CheckMultipleRunsSeq4) {
for (uint32_t i = 0; i < inferences; i++) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1267,7 +1267,7 @@ TEST_P(RunSeqTests, CheckTurboWithMultipleRunsSeq) {
for (int i = inferences - 1; i >= 0; i--) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1328,7 +1328,7 @@ TEST_P(BatchingRunSeqTests, CheckMultipleBatchingRunsSeq) {
for (uint32_t i = 0; i < inferences; i++) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1371,7 +1371,7 @@ TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun0) {
float expected_result = static_cast<float>(batch_size) + 1.f;
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor.data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << batch_size << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -1397,7 +1397,7 @@ TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun0) {
EXPECT_EQ(output_test_tensor.get_size(), input_host_tensor.get_size());
for (size_t j = 0; j < output_test_tensor.get_size(); ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -1436,7 +1436,7 @@ TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun1) {
float expected_result = static_cast<float>(batch_size) + 1.f;
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor.data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << batch_size << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -1462,7 +1462,7 @@ TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun1) {
EXPECT_EQ(output_test_tensor.get_size(), input_host_tensor.get_size());
for (size_t j = 0; j < output_test_tensor.get_size(); ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -1499,7 +1499,7 @@ TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRun2) {
float expected_result = static_cast<float>(batch_size) + 1.f;
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor.data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << batch_size << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -1554,7 +1554,7 @@ TEST_P(DynamicBatchingTests, DynamicCheckMultipleBatchingRunsSeq) {
for (uint32_t i = 0; i < inferences; i++) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Run=" << z << "Output=" << i << " Expected=" << expected_result
<< ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -1621,7 +1621,7 @@ TEST_P(SetShapeInferRunTests, checkResultsAfterIOBlobReallocation) {
auto* actual = first_output_tensor.data<float>();
for (size_t i = 0; i < shape_size; ++i) {
- EXPECT_NEAR(actual[i], 6.f, 1e-5) << "Expected=6, actual=" << actual[i] << " for index " << i;
+ ASSERT_NEAR(actual[i], 6.f, 1e-5) << "Expected=6, actual=" << actual[i] << " for index " << i;
}
// imitates blob reallocation
@@ -1643,7 +1643,7 @@ TEST_P(SetShapeInferRunTests, checkResultsAfterIOBlobReallocation) {
actual = second_output_tensor.data<float>();
for (size_t i = 0; i < shape_size; ++i) {
- EXPECT_NEAR(actual[i], 10.f, 1e-5) << "Expected=10, actual=" << actual[i] << " for index " << i;
+ ASSERT_NEAR(actual[i], 10.f, 1e-5) << "Expected=10, actual=" << actual[i] << " for index " << i;
}
}
@@ -1680,7 +1680,7 @@ TEST_P(SetShapeInferRunTests, checkResultsAfterStateTensorsReallocation) {
auto output_tensor = inference_request.get_tensor("sigmod_state");
auto output_data = output_tensor.data<float>();
for (size_t i = 0; i < output_tensor.get_size(); i++) {
- EXPECT_NEAR(0.5f, output_data[i], 1e-5);
+ ASSERT_NEAR(0.5f, output_data[i], 1e-5);
}
auto states = inference_request.query_state();
@@ -1692,7 +1692,7 @@ TEST_P(SetShapeInferRunTests, checkResultsAfterStateTensorsReallocation) {
ASSERT_TRUE(last_state_size != 0) << "State size should not be 0";
for (size_t i = 0; i < last_state_size; ++i) {
- EXPECT_NEAR(0.0, last_state_data[i], 1e-5);
+ ASSERT_NEAR(0.0, last_state_data[i], 1e-5);
}
}
@@ -1739,7 +1739,7 @@ TEST_P(SetShapeInferRunTests, checkResultsAfterStateTensorsReallocation) {
ASSERT_TRUE(last_state_size != 0) << "State size should not be 0";
for (size_t i = 0; i < last_state_size; ++i) {
- EXPECT_NEAR(input_data[i], last_state_data[i], 1e-5);
+ ASSERT_NEAR(input_data[i], last_state_data[i], 1e-5);
}
}
}
@@ -1848,7 +1848,7 @@ TEST_P(CpuVaTensorsTests, SetMultiplePageAllignedTensors) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
EXPECT_EQ(output_tensor_data, output_data[i]);
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Output=" << i << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -1920,7 +1920,7 @@ TEST_P(CpuVaTensorsTests, SetMultipleAllignedAndNotAllignedTensors) {
for (int i = 0; i < inferences; i++) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Output=" << i << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -2003,7 +2003,7 @@ TEST_P(CpuVaTensorsTests, SetMultipleRemoteAllignedAndNotAllignedTensors) {
for (int i = 0; i < inferences; i++) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor[i].data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< "Output=" << i << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
<< " for index " << j;
}
@@ -2069,13 +2069,13 @@ TEST_P(CpuVaTensorsTests, SetAndDestroyDifferentAlignedTensors) {
auto* output_tensor_data = reinterpret_cast<float*>(output_tensor0.data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< " Expected=" << expected_result << ", actual=" << output_tensor_data[j] << " for index " << j;
}
output_tensor_data = reinterpret_cast<float*>(output_tensor1.data());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
<< " Expected=" << expected_result << ", actual=" << output_tensor_data[j] << " for index " << j;
}
@@ -2136,7 +2136,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterStateTensorsUseImportCpuVa0) {
auto output_tensor = inference_request.get_tensor("sigmod_state");
auto output_data = output_tensor.data<float>();
for (size_t i = 0; i < output_tensor.get_size(); i++) {
- EXPECT_NEAR(0.5f, output_data[i], 1e-5);
+ ASSERT_NEAR(0.5f, output_data[i], 1e-5);
}
states = inference_request.query_state();
@@ -2166,11 +2166,11 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterStateTensorsUseImportCpuVa0) {
auto get_state_data = static_cast<float*>(l0_host_tensor.data());
for (size_t i = 0; i < get_tensor_state.get_size(); ++i) {
- EXPECT_NEAR(0.0, get_state_data[i], 1e-5);
- EXPECT_NEAR(0.0, state_data[0][i], 1e-5);
+ ASSERT_NEAR(0.0, get_state_data[i], 1e-5);
+ ASSERT_NEAR(0.0, state_data[0][i], 1e-5);
- EXPECT_NEAR(input_data[i], state_data[1][i], 1e-5);
- EXPECT_NEAR(input_data[i], state_data[2][i], 1e-5);
+ ASSERT_NEAR(input_data[i], state_data[1][i], 1e-5);
+ ASSERT_NEAR(input_data[i], state_data[2][i], 1e-5);
}
inference_request = {};
@@ -2234,7 +2234,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterStateTensorsUseImportCpuVa1) {
auto output_tensor = inference_request.get_tensor("sigmod_state");
auto output_data = output_tensor.data<float>();
for (size_t i = 0; i < output_tensor.get_size(); i++) {
- EXPECT_NEAR(0.5f, output_data[i], 1e-5);
+ ASSERT_NEAR(0.5f, output_data[i], 1e-5);
}
states = inference_request.query_state();
@@ -2264,11 +2264,11 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterStateTensorsUseImportCpuVa1) {
auto get_state_data = static_cast<float*>(l0_host_tensor.data());
for (size_t i = 0; i < get_tensor_state.get_size(); ++i) {
- EXPECT_NEAR(0.0, get_state_data[i], 1e-5);
- EXPECT_NEAR(0.0, state_data[0][i], 1e-5);
+ ASSERT_NEAR(0.0, get_state_data[i], 1e-5);
+ ASSERT_NEAR(0.0, state_data[0][i], 1e-5);
- EXPECT_NEAR(input_data[i], state_data[1][i], 1e-5);
- EXPECT_NEAR(input_data[i], state_data[2][i], 1e-5);
+ ASSERT_NEAR(input_data[i], state_data[1][i], 1e-5);
+ ASSERT_NEAR(input_data[i], state_data[2][i], 1e-5);
}
inference_request = {};
@@ -2333,7 +2333,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterRawMemoryIsDestroyedAndReallocatedAft
logs.clear();
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
+ ASSERT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
<< "Run " << i << ": Expected=" << input_data[j] + 1.0f << ", actual=" << output_data[j]
<< " for index " << j;
}
@@ -2400,7 +2400,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterRunningWithSameRawMemoryMultipleTimes
logs.clear();
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
+ ASSERT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
<< "Run " << i << ": Expected=" << input_data[j] + 1.0f << ", actual=" << output_data[j]
<< " for index " << j;
}
@@ -2464,7 +2464,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterRunningWithSameZeroTensorMultipleTime
logs.clear();
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
+ ASSERT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
<< "Run " << i << ": Expected=" << input_data[j] + 1.0f << ", actual=" << output_data[j]
<< " for index " << j;
}
@@ -2527,7 +2527,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterRunningWithSameZeroHostTensorMultiple
logs.clear();
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
+ ASSERT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
<< "Run " << i << ": Expected=" << input_data[j] + 1.0f << ", actual=" << output_data[j]
<< " for index " << j;
}
@@ -2570,7 +2570,7 @@ TEST_P(CpuVaTensorsTests, checkResultsAfterRunningWithSameRawMemoryMultipleTimes
OV_ASSERT_NO_THROW(inference_request.infer());
for (size_t j = 0; j < shape_size; ++j) {
- EXPECT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
+ ASSERT_NEAR(output_data[j], input_data[j] + 1.0f, 1e-5)
<< "Run " << i << ": Expected=" << input_data[j] + 1.0f << ", actual=" << output_data[j]
<< " for index " << j;
}
@@ -2815,6 +2815,52 @@ TEST_P(DynamicBoundsTests, ExpectErrorFromWrongTensorShape) {
HasSubstr("The tensor shape is not compatible with the model input/output shape"));
}
+using NumStreamsTests = InferRequestRunTests;
+
+TEST_P(NumStreamsTests, RunWithDifferentNumStreamsCheckResults) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ auto shape = Shape{1, 2, 64, 64};
+ auto shape_size = ov::shape_size(shape);
+ auto model = createModel(element::f32, shape, "N...");
+
+ auto compiled_model = core->compile_model(model, target_device, configuration);
+ const uint32_t inferences = 32;
+ std::array<ov::InferRequest, inferences> inference_request;
+
+ for (uint32_t i = 0; i < inferences; i++) {
+ inference_request[i] = compiled_model.create_infer_request();
+
+ auto input_tensor = inference_request[i].get_input_tensor();
+ auto* input_data = reinterpret_cast<float*>(input_tensor.data());
+ for (size_t j = 0; j < shape_size; ++j) {
+ input_data[j] = static_cast<float>(i);
+ }
+ }
+
+ for (uint32_t i = 0; i < inferences; i++) {
+ OV_ASSERT_NO_THROW(inference_request[i].infer());
+ }
+
+ for (uint32_t i = 0; i < inferences; i++) {
+ OV_ASSERT_NO_THROW(inference_request[i].start_async());
+ }
+
+ for (uint32_t i = 0; i < inferences; i++) {
+ OV_ASSERT_NO_THROW(inference_request[i].wait());
+ }
+
+ for (uint32_t i = 0; i < inferences; i++) {
+ float expected_result = static_cast<float>(i) + 1.f;
+ auto output_tensor = inference_request[i].get_output_tensor();
+ auto* output_tensor_data = reinterpret_cast<float*>(output_tensor.data());
+ for (size_t j = 0; j < shape_size; ++j) {
+ ASSERT_NEAR(output_tensor_data[j], expected_result, 1e-5)
+ << "Inference=" << i << " Expected=" << expected_result << ", actual=" << output_tensor_data[j]
+ << " for index " << j;
+ }
+ }
+}
+
} // namespace behavior
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp b/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp
index d5f1434c379..16136939ab1 100644
--- a/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp
+++ b/src/plugins/intel_npu/tests/functional/shared_tests_instances/behavior/ov_plugin/properties_tests.cpp
@@ -78,7 +78,7 @@ const std::vector<ov::AnyMap> compat_CorrectPluginDefaultMutableProperties = {
{{ov::hint::num_requests.name(), 1u}},
{{ov::log::level.name(), getTestsLogLevelFromEnvironmentOr(ov::log::Level::WARNING)}},
{{ov::device::id.name(), ""}},
- {{ov::num_streams.name(), ov::streams::Num(1)}},
+ {{ov::num_streams.name(), ov::streams::AUTO}},
};
const std::vector<ov::AnyMap> CorrectPluginDefaultMutableProperties = {
@@ -117,7 +117,6 @@ const std::vector<ov::AnyMap> CorrectCompiledModelProperties = {
};
const std::vector<ov::AnyMap> IncorrectImmutableProperties = {
- {{ov::streams::num.name(), ov::streams::Num(2)}},
{{ov::optimal_number_of_infer_requests.name(), 4}},
{{ov::intel_npu::device_alloc_mem_size.name(), 1024}},
{{ov::intel_npu::device_total_mem_size.name(), 2048}},
diff --git a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml
index 5d6038e6dd8..71df259e4eb 100644
--- a/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml
+++ b/src/plugins/intel_npu/tests/functional/shared_tests_instances/npu_skip_func_tests.xml
@@ -186,7 +186,6 @@ Example:
<skip_config>
<message>TensorIterator layer is not supported</message>
<filters>
- <filter>.*ReturnResultNotReadyFromWaitInAsyncModeForTooSmallTimeout.*</filter>
<filter>.*OVInferRequestDynamicTests.*</filter>
<filter>.*OVInferenceChaining.*</filter>
</filters>
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index cbd054beda4..c29ba096479 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -40,6 +40,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/thirdparty/level_zero/level-zero/include
OBJECT_FILES
# plugin/src
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/executor.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/src/metadata.cpp
# npuw core
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -133,6 +134,7 @@ install(TARGETS ${TARGET_NAME}
)
target_sources(${TARGET_NAME} PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/npu/executor_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_compiled_model_graph_options_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/stored_tokens_state_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/lincache_utils_test.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npu/executor_test.cpp b/src/plugins/intel_npu/tests/unit/npu/executor_test.cpp
new file mode 100644
index 00000000000..977541abdfc
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npu/executor_test.cpp
@@ -0,0 +1,595 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "executor.hpp"
+
+#include <gtest/gtest.h>
+
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+#include <functional>
+#include <future>
+#include <memory>
+#include <mutex>
+#include <set>
+#include <stdexcept>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "openvino/openvino.hpp"
+#include "openvino/runtime/common.hpp"
+#include "openvino/runtime/iasync_infer_request.hpp"
+#include "openvino/runtime/icompiled_model.hpp"
+#include "openvino/runtime/isync_infer_request.hpp"
+#include "openvino/runtime/ivariable_state.hpp"
+
+namespace {
+
+using namespace std::chrono_literals;
+
+class SharedState {
+public:
+ std::atomic<int> inferCalls{0};
+ std::atomic<bool> failInfer{false};
+};
+
+class TestPlugin final : public ov::IPlugin {
+public:
+ std::shared_ptr<ov::ICompiledModel> compile_model(const std::shared_ptr<const ov::Model>&,
+ const ov::AnyMap&) const override {
+ OPENVINO_THROW("Not implemented in unit test plugin");
+ }
+
+ std::shared_ptr<ov::ICompiledModel> compile_model(const std::shared_ptr<const ov::Model>&,
+ const ov::AnyMap&,
+ const ov::SoPtr<ov::IRemoteContext>&) const override {
+ OPENVINO_THROW("Not implemented in unit test plugin");
+ }
+
+ void set_property(const ov::AnyMap&) override {}
+
+ ov::Any get_property(const std::string&, const ov::AnyMap&) const override {
+ return {};
+ }
+
+ ov::SoPtr<ov::IRemoteContext> create_context(const ov::AnyMap&) const override {
+ return {};
+ }
+
+ ov::SoPtr<ov::IRemoteContext> get_default_context(const ov::AnyMap&) const override {
+ return {};
+ }
+
+ std::shared_ptr<ov::ICompiledModel> import_model(std::istream&, const ov::AnyMap&) const override {
+ OPENVINO_THROW("Not implemented in unit test plugin");
+ }
+
+ std::shared_ptr<ov::ICompiledModel> import_model(std::istream&,
+ const ov::SoPtr<ov::IRemoteContext>&,
+ const ov::AnyMap&) const override {
+ OPENVINO_THROW("Not implemented in unit test plugin");
+ }
+
+ std::shared_ptr<ov::ICompiledModel> import_model(const ov::Tensor&, const ov::AnyMap&) const override {
+ OPENVINO_THROW("Not implemented in unit test plugin");
+ }
+
+ std::shared_ptr<ov::ICompiledModel> import_model(const ov::Tensor&,
+ const ov::SoPtr<ov::IRemoteContext>&,
+ const ov::AnyMap&) const override {
+ OPENVINO_THROW("Not implemented in unit test plugin");
+ }
+
+ ov::SupportedOpsMap query_model(const std::shared_ptr<const ov::Model>&, const ov::AnyMap&) const override {
+ return {};
+ }
+};
+
+class TestCompiledModel;
+
+class TestSyncInferRequest final : public ov::ISyncInferRequest {
+public:
+ TestSyncInferRequest(std::shared_ptr<const ov::ICompiledModel> compiled_model, std::shared_ptr<SharedState> state)
+ : ov::ISyncInferRequest(std::move(compiled_model)),
+ m_state(std::move(state)) {}
+
+ void infer() override {
+ m_state->inferCalls.fetch_add(1);
+ if (m_state->failInfer.exchange(false)) {
+ OPENVINO_THROW("sync infer failure");
+ }
+ }
+
+ std::vector<ov::ProfilingInfo> get_profiling_info() const override {
+ return {};
+ }
+
+ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {
+ return {};
+ }
+
+protected:
+ void check_tensors() const override {
+ // This test request does not consume model tensors; it validates async callback flow only.
+ }
+
+private:
+ std::shared_ptr<SharedState> m_state;
+};
+
+class TestCompiledModel final : public ov::ICompiledModel {
+public:
+ explicit TestCompiledModel(std::shared_ptr<SharedState> state)
+ : ov::ICompiledModel(build_model(), make_test_plugin()),
+ m_state(std::move(state)),
+ m_model(build_model()) {}
+
+ std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {
+ auto self = std::static_pointer_cast<const TestCompiledModel>(shared_from_this());
+ return std::make_shared<TestSyncInferRequest>(std::move(self), m_state);
+ }
+
+ std::shared_ptr<ov::IAsyncInferRequest> create_infer_request() const override {
+ return std::make_shared<ov::IAsyncInferRequest>(create_sync_infer_request(),
+ intel_npu::make_executor("executor_test_task", 1),
+ intel_npu::make_executor("executor_test_callback", 1));
+ }
+
+ void export_model(std::ostream&) const override {}
+
+ std::shared_ptr<const ov::Model> get_runtime_model() const override {
+ return m_model;
+ }
+
+ void set_property(const ov::AnyMap&) override {}
+
+ ov::Any get_property(const std::string& name) const override {
+ if (name == ov::execution_devices.name()) {
+ return std::vector<std::string>{"NPU"};
+ }
+ OPENVINO_THROW("Unsupported property: ", name);
+ }
+
+private:
+ static std::shared_ptr<const ov::IPlugin> make_test_plugin() {
+ static const auto plugin = std::make_shared<TestPlugin>();
+ return plugin;
+ }
+
+ static std::shared_ptr<ov::Model> build_model() {
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1});
+ auto result = std::make_shared<ov::op::v0::Result>(param);
+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param});
+ }
+
+ std::shared_ptr<SharedState> m_state;
+ std::shared_ptr<ov::Model> m_model;
+};
+
+bool wait_until(const std::function<bool()>& pred) {
+ while (!pred()) {
+ std::this_thread::yield();
+ }
+ return true;
+}
+
+TEST(NPUExecutorTests, InlineModeRunsOnCallerThread) {
+ auto exec = intel_npu::make_executor("inline", 0, false, 10ms);
+
+ std::thread::id taskThread{};
+ exec->run([&] {
+ taskThread = std::this_thread::get_id();
+ });
+
+ EXPECT_EQ(taskThread, std::this_thread::get_id());
+}
+
+TEST(NPUExecutorTests, InlineModeSwallowsTaskExceptions) {
+ auto exec = intel_npu::make_executor("inline_throw", 0, false, 10ms);
+
+ std::atomic<bool> taskRan{false};
+
+ EXPECT_NO_THROW(exec->run([&] {
+ taskRan = true;
+ throw std::runtime_error("inline_failure");
+ }));
+
+ EXPECT_TRUE(taskRan.load());
+
+ std::atomic<bool> followUpRan{false};
+ EXPECT_NO_THROW(exec->run([&] {
+ followUpRan = true;
+ }));
+ EXPECT_TRUE(followUpRan.load());
+}
+
+TEST(NPUExecutorTests, AdaptiveModeGrowsForQueuedWork) {
+ auto exec = intel_npu::make_executor("grow", 0, true, 200ms);
+
+ std::mutex m;
+ std::condition_variable cv;
+ bool release = false;
+ int started = 0;
+
+ auto blockingTask = [&] {
+ {
+ std::lock_guard<std::mutex> lock(m);
+ ++started;
+ }
+ cv.notify_all();
+
+ std::unique_lock<std::mutex> lock(m);
+ cv.wait(lock, [&] {
+ return release;
+ });
+ };
+
+ exec->run(blockingTask);
+ exec->run(blockingTask);
+
+ // EXPECT (non-fatal) so the release block always runs,
+ // preventing the destructor from deadlocking on blocked worker threads.
+ EXPECT_TRUE(wait_until([&] {
+ std::lock_guard<std::mutex> lock(m);
+ return started == 2;
+ }));
+
+ {
+ std::lock_guard<std::mutex> lock(m);
+ release = true;
+ }
+ cv.notify_all();
+}
+
+TEST(NPUExecutorTests, FixedModeDoesNotUseMoreThanConfiguredWorkers) {
+ constexpr int workers = 2;
+ constexpr int tasksCount = 6;
+ auto exec = intel_npu::make_executor("fixed_workers", workers, false, 200ms);
+
+ std::mutex m;
+ std::condition_variable cv;
+ bool release = false;
+ int started = 0;
+ int completed = 0;
+ std::set<std::thread::id> workerThreads;
+
+ for (int i = 0; i < tasksCount; ++i) {
+ exec->run([&] {
+ {
+ std::lock_guard<std::mutex> lock(m);
+ ++started;
+ workerThreads.insert(std::this_thread::get_id());
+ }
+ cv.notify_all();
+
+ std::unique_lock<std::mutex> lock(m);
+ cv.wait(lock, [&] {
+ return release;
+ });
+
+ ++completed;
+ cv.notify_all();
+ });
+ }
+
+ // EXPECT (non-fatal) so the release block always runs,
+ // preventing the destructor from deadlocking on 6 blocked worker tasks.
+ EXPECT_TRUE(wait_until([&] {
+ std::lock_guard<std::mutex> lock(m);
+ return started >= workers;
+ }));
+
+ {
+ std::lock_guard<std::mutex> lock(m);
+ release = true;
+ }
+ cv.notify_all();
+
+ EXPECT_TRUE(wait_until([&] {
+ std::lock_guard<std::mutex> lock(m);
+ return completed == tasksCount;
+ }));
+
+ std::lock_guard<std::mutex> lock(m);
+ EXPECT_LE(workerThreads.size(), static_cast<size_t>(workers));
+}
+
+TEST(NPUExecutorTests, AdaptiveModeGrowShrinkAcrossMultipleBursts) {
+ auto exec = intel_npu::make_executor("grow_shrink_cycles", 1, true, 30ms);
+
+ for (int cycle = 0; cycle < 5; ++cycle) {
+ std::mutex m;
+ std::condition_variable cv;
+ bool release = false;
+ int started = 0;
+ int completed = 0;
+
+ auto blockingTask = [&] {
+ {
+ std::lock_guard<std::mutex> lock(m);
+ ++started;
+ }
+ cv.notify_all();
+
+ std::unique_lock<std::mutex> lock(m);
+ cv.wait(lock, [&] {
+ return release;
+ });
+
+ ++completed;
+ cv.notify_all();
+ };
+
+ exec->run(blockingTask);
+ exec->run(blockingTask);
+
+ // EXPECT (non-fatal) so the release block always runs,
+ // preventing the destructor from deadlocking on blocked worker threads.
+ EXPECT_TRUE(wait_until([&] {
+ std::lock_guard<std::mutex> lock(m);
+ return started == 2;
+ }));
+
+ {
+ std::lock_guard<std::mutex> lock(m);
+ release = true;
+ }
+ cv.notify_all();
+
+ EXPECT_TRUE(wait_until([&] {
+ std::lock_guard<std::mutex> lock(m);
+ return completed == 2;
+ }));
+
+ std::this_thread::yield();
+ }
+}
+
+TEST(NPUExecutorTests, DestructorWaitsForInFlightTaskCompletion) {
+ auto exec = intel_npu::make_executor("destroy_waits", 1, false, 200ms);
+
+ std::mutex m;
+ std::condition_variable cv;
+ bool started = false;
+ bool release = false;
+ std::atomic<bool> finished{false};
+ std::atomic<bool> destructorReturned{false};
+
+ exec->run([&] {
+ {
+ std::lock_guard<std::mutex> lock(m);
+ started = true;
+ }
+ cv.notify_all();
+
+ std::unique_lock<std::mutex> lock(m);
+ cv.wait(lock, [&] {
+ return release;
+ });
+ finished = true;
+ });
+
+ ASSERT_TRUE(wait_until([&] {
+ std::lock_guard<std::mutex> lock(m);
+ return started;
+ }));
+
+ std::thread destroyer([&] {
+ exec.reset();
+ destructorReturned = true;
+ });
+
+ // Do not use sleep_for to assert destructorReturned is still false — that
+ // is a racy negative assertion that fails on a loaded CI machine where the
+ // destroyer thread may not be scheduled within the sleep window.
+ // The deterministic guarantee is captured below: after destroyer.join(),
+ // finished must be true, proving the destructor waited for the task.
+ {
+ std::lock_guard<std::mutex> lock(m);
+ release = true;
+ }
+ cv.notify_all();
+
+ destroyer.join();
+ EXPECT_TRUE(finished.load());
+ EXPECT_TRUE(destructorReturned.load());
+}
+
+TEST(NPUExecutorTests, AdaptiveModeWithZeroBaselineRunsOffCallerThread) {
+ auto exec = intel_npu::make_executor("adaptive_zero_baseline", 0, true, 200ms);
+
+ const auto callerId = std::this_thread::get_id();
+ std::thread::id workerId{};
+ std::promise<void> done;
+ auto doneFuture = done.get_future();
+
+ exec->run([&] {
+ workerId = std::this_thread::get_id();
+ done.set_value();
+ });
+
+ doneFuture.wait();
+ EXPECT_NE(workerId, std::thread::id{});
+ EXPECT_NE(workerId, callerId);
+}
+
+TEST(NPUExecutorTests, ReentrantSubmissionFromWorkerDoesNotDeadlock) {
+ auto exec = intel_npu::make_executor("reentrant_submit", 1, false, 200ms);
+
+ std::mutex sequenceMutex;
+ std::vector<std::string> sequence;
+
+ std::promise<void> parentDone;
+ std::promise<void> childDone;
+ auto parentFuture = parentDone.get_future();
+ auto childFuture = childDone.get_future();
+
+ exec->run([&] {
+ {
+ std::lock_guard<std::mutex> lock(sequenceMutex);
+ sequence.emplace_back("parent_start");
+ }
+
+ exec->run([&] {
+ {
+ std::lock_guard<std::mutex> lock(sequenceMutex);
+ sequence.emplace_back("child");
+ }
+ childDone.set_value();
+ });
+
+ {
+ std::lock_guard<std::mutex> lock(sequenceMutex);
+ sequence.emplace_back("parent_end");
+ }
+ parentDone.set_value();
+ });
+
+ parentFuture.wait();
+ childFuture.wait();
+
+ ASSERT_EQ(sequence.size(), 3U);
+ EXPECT_EQ(sequence[0], "parent_start");
+ EXPECT_EQ(sequence[1], "parent_end");
+ EXPECT_EQ(sequence[2], "child");
+}
+
+TEST(NPUExecutorTests, StressManyProducersNoTaskLoss) {
+ auto exec = intel_npu::make_executor("stress_many_submitters", 4, false, 200ms);
+
+ constexpr int producers = 4;
+ constexpr int tasksPerProducer = 80;
+ constexpr int expectedSuccessesPerProducer = tasksPerProducer;
+
+ std::atomic<int> successfulTasks{0};
+
+ std::vector<std::thread> submitters;
+ submitters.reserve(producers);
+
+ for (int submitterIdx = 0; submitterIdx < producers; ++submitterIdx) {
+ submitters.emplace_back([&] {
+ for (int i = 0; i < tasksPerProducer; ++i) {
+ exec->run([&] {
+ successfulTasks.fetch_add(1);
+ });
+ }
+ });
+ }
+
+ for (auto& th : submitters) {
+ th.join();
+ }
+
+ ASSERT_TRUE(wait_until([&] {
+ return successfulTasks.load() == producers * expectedSuccessesPerProducer;
+ }));
+
+ EXPECT_EQ(successfulTasks.load(), producers * expectedSuccessesPerProducer);
+}
+
+TEST(NPUExecutorTests, InlineModeSwallowsCustomExceptionType) {
+ class CustomDeferredError final : public std::runtime_error {
+ public:
+ explicit CustomDeferredError(const std::string& whatArg) : std::runtime_error(whatArg) {}
+ };
+
+ auto exec = intel_npu::make_executor("typed_exception", 0, false, 200ms);
+
+ std::atomic<bool> taskRan{false};
+ EXPECT_NO_THROW(exec->run([&] {
+ taskRan = true;
+ throw CustomDeferredError("typed_error");
+ }));
+
+ EXPECT_TRUE(taskRan.load());
+}
+
+TEST(NPUExecutorTests, AdaptiveModeTinyIdleTimeoutRemainsStable) {
+ auto exec = intel_npu::make_executor("tiny_idle_timeout", 1, true, 1ms);
+
+ constexpr int totalTasks = 200;
+ std::atomic<int> completed{0};
+
+ for (int i = 0; i < totalTasks; ++i) {
+ exec->run([&, i] {
+ if (i % 3 == 0) {
+ std::this_thread::yield();
+ }
+ completed.fetch_add(1);
+ });
+ }
+
+ ASSERT_TRUE(wait_until([&] {
+ return completed.load() == totalTasks;
+ }));
+}
+
+TEST(NPUExecutorTests, ResettingOneOwnerDoesNotStopOtherOwners) {
+ auto ownerA = intel_npu::make_executor("shared_owner_reset", 1, false, 200ms);
+ auto ownerB = ownerA;
+
+ std::thread releaser([&] {
+ ownerA.reset();
+ });
+ releaser.join();
+
+ std::atomic<bool> ran{false};
+ ownerB->run([&] {
+ ran = true;
+ });
+
+ ASSERT_TRUE(wait_until([&] {
+ return ran.load();
+ }));
+}
+
+TEST(NPUExecutorTests, AsyncInferRequestPipelineSuccessCallback) {
+ auto state = std::make_shared<SharedState>();
+ auto compiledModel = std::make_shared<TestCompiledModel>(state);
+ auto asyncRequest = compiledModel->create_infer_request();
+
+ std::atomic<bool> callbackCalled{false};
+ std::atomic<bool> callbackHadException{true};
+
+ asyncRequest->set_callback([&](std::exception_ptr ex) {
+ callbackCalled = true;
+ callbackHadException = (ex != nullptr);
+ });
+
+ asyncRequest->start_async();
+ asyncRequest->wait();
+
+ EXPECT_TRUE(callbackCalled.load());
+ EXPECT_FALSE(callbackHadException.load());
+ EXPECT_EQ(state->inferCalls.load(), 1);
+}
+
+TEST(NPUExecutorTests, AsyncInferRequestPipelineFailureCallback) {
+ auto state = std::make_shared<SharedState>();
+ auto compiledModel = std::make_shared<TestCompiledModel>(state);
+ auto asyncRequest = compiledModel->create_infer_request();
+
+ state->failInfer = true;
+
+ std::atomic<bool> callbackCalled{false};
+ std::atomic<bool> callbackHadException{false};
+
+ asyncRequest->set_callback([&](std::exception_ptr ex) {
+ callbackCalled = true;
+ callbackHadException = (ex != nullptr);
+ });
+
+ asyncRequest->start_async();
+ ASSERT_THROW(asyncRequest->wait(), std::exception);
+
+ ASSERT_TRUE(wait_until([&] {
+ return callbackCalled.load();
+ }));
+ EXPECT_TRUE(callbackHadException.load());
+ EXPECT_EQ(state->inferCalls.load(), 1);
+}
+
+} // namespace