OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CORE] Make sure callback finishes execution before running it the second time for the next run in separate thread (#36304)
Bogdan Pereanu4089686065a2
diff --git a/src/inference/dev_api/openvino/runtime/iasync_infer_request.hpp b/src/inference/dev_api/openvino/runtime/iasync_infer_request.hppindex 6d066cc95a7..43cc1724cb6 100644--- a/src/inference/dev_api/openvino/runtime/iasync_infer_request.hpp+++ b/src/inference/dev_api/openvino/runtime/iasync_infer_request.hpp@@ -214,7 +214,7 @@ private:_this->m_callback = m_callback;}IAsyncInferRequest* _this = nullptr;- std::function<void(std::exception_ptr)> m_callback;+ std::shared_ptr<std::function<void(std::exception_ptr)>> m_callback;};void run_first_stage(const Pipeline::iterator itBeginStage,@@ -230,7 +230,7 @@ private:check_tensors();InferState state = InferState::IDLE;{- std::lock_guard<std::mutex> lock{m_mutex};+ std::lock_guard lock{m_mutex};state = m_state;switch (m_state) {case InferState::BUSY:@@ -277,7 +277,7 @@ private:std::shared_ptr<ov::threading::ITaskExecutor>m_sync_callback_executor; //!< Used to run post inference callback in synchronous piplinemutable std::mutex m_mutex;- std::function<void(std::exception_ptr)> m_callback;+ std::shared_ptr<std::function<void(std::exception_ptr)>> m_callback;};} // namespace ovdiff --git a/src/inference/src/dev/iasync_infer_request.cpp b/src/inference/src/dev/iasync_infer_request.cppindex 323ebab688c..683b865821b 100644--- a/src/inference/src/dev/iasync_infer_request.cpp+++ b/src/inference/src/dev/iasync_infer_request.cpp@@ -66,7 +66,7 @@ ov::IAsyncInferRequest::IAsyncInferRequest(const std::shared_ptr<IInferRequest>&void ov::IAsyncInferRequest::wait() {// Just use the last '_futures' member to wait pipeline completionauto future = [this] {- std::lock_guard<std::mutex> lock{m_mutex};+ std::lock_guard lock{m_mutex};return m_futures.empty() ? std::shared_future<void>{} : m_futures.back();}();if (future.valid()) {@@ -79,7 +79,7 @@ bool ov::IAsyncInferRequest::wait_for(const std::chrono::milliseconds& timeout)// Just use the last '_futures' member to wait pipeline completionauto future = [this] {- std::lock_guard<std::mutex> lock{m_mutex};+ std::lock_guard lock{m_mutex};return m_futures.empty() ? std::shared_future<void>{} : m_futures.back();}();@@ -98,7 +98,7 @@ bool ov::IAsyncInferRequest::wait_for(const std::chrono::milliseconds& timeout)}void ov::IAsyncInferRequest::cancel() {- std::lock_guard<std::mutex> lock{m_mutex};+ std::lock_guard lock{m_mutex};if (m_state == InferState::BUSY) {m_state = InferState::CANCELLED;}@@ -106,8 +106,8 @@ void ov::IAsyncInferRequest::cancel() {void ov::IAsyncInferRequest::set_callback(std::function<void(std::exception_ptr)> callback) {check_state();- std::lock_guard<std::mutex> lock{m_mutex};- m_callback = std::move(callback);+ std::lock_guard lock{m_mutex};+ m_callback = std::make_shared<std::function<void(std::exception_ptr)>>(std::move(callback));}std::vector<ov::SoPtr<ov::IVariableState>> ov::IAsyncInferRequest::query_state() const {@@ -160,23 +160,19 @@ ov::threading::Task ov::IAsyncInferRequest::make_next_stage_task(if ((itEndStage == itNextStage) || (nullptr != currentException)) {auto lastStageTask = [this, currentException]() mutable {std::promise<void> promise;- std::function<void(std::exception_ptr)> callback;+ std::shared_ptr<std::function<void(std::exception_ptr)>> callback;{- std::lock_guard<std::mutex> lock{m_mutex};+ std::lock_guard lock{m_mutex};m_state = InferState::IDLE;promise = std::move(m_promise);- std::swap(callback, m_callback);+ callback = m_callback;}- if (callback) {+ if (callback && *callback) {try {- callback(currentException);+ (*callback)(currentException);} catch (...) {currentException = std::current_exception();}- std::lock_guard<std::mutex> lock{m_mutex};- if (!m_callback) {- std::swap(callback, m_callback);- }}if (nullptr == currentException) {promise.set_value();diff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.cpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.cppindex 1b6cb530e80..8b93aca861b 100644--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.cpp@@ -9,27 +9,10 @@namespace {const std::vector<ov::AnyMap> configs = {{}};-const std::vector<ov::AnyMap> multiConfigs = {{ov::device::priorities(ov::test::utils::DEVICE_NPU),- ov::device::properties(ov::test::utils::DEVICE_NPU, ov::AnyMap{})}};--const std::vector<ov::AnyMap> autoConfigs = {{ov::device::priorities(ov::test::utils::DEVICE_NPU),- ov::device::properties(ov::test::utils::DEVICE_NPU, ov::AnyMap{})}};-INSTANTIATE_TEST_SUITE_P(compatibility_smoke_BehaviorTests,OVInferRequestCallbackTestsNPU,::testing::Combine(::testing::Values(ov::test::utils::DEVICE_NPU),::testing::ValuesIn(configs)),InferRequestParamsAnyMapTestName::getTestCaseName);-INSTANTIATE_TEST_SUITE_P(compatibility_smoke_Multi_BehaviorTests,- OVInferRequestCallbackTestsNPU,- ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_MULTI),- ::testing::ValuesIn(multiConfigs)),- InferRequestParamsAnyMapTestName::getTestCaseName);--INSTANTIATE_TEST_SUITE_P(compatibility_smoke_Auto_BehaviorTests,- OVInferRequestCallbackTestsNPU,- ::testing::Combine(::testing::Values(ov::test::utils::DEVICE_AUTO),- ::testing::ValuesIn(autoConfigs)),- InferRequestParamsAnyMapTestName::getTestCaseName);} // namespacediff --git a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.hpp b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.hppindex 97fb2304668..e25e524b7d4 100644--- a/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/ov_infer_request/callback.hpp@@ -4,7 +4,10 @@#pragma once+#include <atomic>+#include <chrono>#include <future>+#include <memory>#include "common/utils.hpp"@@ -13,112 +16,60 @@ namespace test {namespace behavior {using OVInferRequestCallbackTestsNPU = OVInferRequestTestsNPU;-TEST_P(OVInferRequestCallbackTestsNPU, canCallAsyncWithCompletionCallback) {+TEST_P(OVInferRequestCallbackTestsNPU, callbackCanCallInfer) {ov::InferRequest req;OV_ASSERT_NO_THROW(req = execNet.create_infer_request());- bool is_called = false;- OV_ASSERT_NO_THROW(req.set_callback([&](std::exception_ptr exception_ptr) {- // HSD_1805940120: Wait on starting callback return HDDL_ERROR_INVAL_TASK_HANDLE- ASSERT_EQ(exception_ptr, nullptr);- is_called = true;- }));- OV_ASSERT_NO_THROW(req.start_async());- OV_ASSERT_NO_THROW(req.wait());- ASSERT_TRUE(is_called);-}--TEST_P(OVInferRequestCallbackTestsNPU, syncInferDoesNotCallCompletionCallback) {- ov::InferRequest req;- OV_ASSERT_NO_THROW(req = execNet.create_infer_request());- bool is_called = false;- req.set_callback([&](std::exception_ptr exception_ptr) {- ASSERT_EQ(nullptr, exception_ptr);- is_called = true;- });- req.infer();- ASSERT_FALSE(is_called);-}-// test that can wait all callbacks on dtor-TEST_P(OVInferRequestCallbackTestsNPU, canStartSeveralAsyncInsideCompletionCallbackWithSafeDtor) {- const int NUM_ITER = 10;- struct TestUserData {- std::atomic<int> numIter = {0};- std::promise<bool> promise;- };- TestUserData data;+ std::atomic<size_t> callback_calls{0};+ std::promise<void> done;+ auto done_future = done.get_future();+ std::atomic_bool done_signaled{false};- ov::InferRequest req;- OV_ASSERT_NO_THROW(req = execNet.create_infer_request());OV_ASSERT_NO_THROW(req.set_callback([&](std::exception_ptr exception_ptr) {- if (exception_ptr) {- data.promise.set_exception(exception_ptr);- } else {- if (data.numIter.fetch_add(1) != NUM_ITER) {- req.start_async();- } else {- data.promise.set_value(true);- }+ ASSERT_EQ(nullptr, exception_ptr);+ callback_calls.fetch_add(1, std::memory_order_relaxed);+ req.infer();++ if (!done_signaled.exchange(true, std::memory_order_relaxed)) {+ done.set_value();}}));- auto future = data.promise.get_future();+OV_ASSERT_NO_THROW(req.start_async());OV_ASSERT_NO_THROW(req.wait());- future.wait();- auto callbackStatus = future.get();- ASSERT_TRUE(callbackStatus);- auto dataNumIter = data.numIter - 1;- ASSERT_EQ(NUM_ITER, dataNumIter);-}-TEST_P(OVInferRequestCallbackTestsNPU, returnGeneralErrorIfCallbackThrowException) {- ov::InferRequest req;- OV_ASSERT_NO_THROW(req = execNet.create_infer_request());- OV_ASSERT_NO_THROW(req.set_callback([](std::exception_ptr) {- OPENVINO_THROW("Throw");- }));- OV_ASSERT_NO_THROW(req.start_async());- ASSERT_THROW(req.wait(), ov::Exception);+ ASSERT_EQ(done_future.wait_for(std::chrono::seconds(30)), std::future_status::ready);+ ASSERT_EQ(callback_calls.load(std::memory_order_relaxed), 1);}-TEST_P(OVInferRequestCallbackTestsNPU, ReturnResultNotReadyFromWaitInAsyncModeForTooSmallTimeout) {+TEST_P(OVInferRequestCallbackTestsNPU, callbackCanCallStartAsyncAndWait) {ov::InferRequest req;OV_ASSERT_NO_THROW(req = execNet.create_infer_request());- std::promise<std::chrono::system_clock::time_point> callbackTimeStamp;- auto callbackTimeStampFuture = callbackTimeStamp.get_future();- // add a callback to the request and capture the timestamp++ std::atomic<size_t> callback_calls{0};+ std::promise<void> nested_done;+ auto nested_done_future = nested_done.get_future();+ std::atomic_bool nested_done_signaled{false};+OV_ASSERT_NO_THROW(req.set_callback([&](std::exception_ptr exception_ptr) {- if (exception_ptr) {- callbackTimeStamp.set_exception(exception_ptr);- } else {- callbackTimeStamp.set_value(std::chrono::system_clock::now());+ ASSERT_EQ(nullptr, exception_ptr);+ const auto call_index = callback_calls.fetch_add(1, std::memory_order_relaxed);++ if (call_index == 0) {+ req.start_async();+ req.wait();+ } else if (call_index == 1) {+ if (!nested_done_signaled.exchange(true, std::memory_order_relaxed)) {+ nested_done.set_value();+ }}}));- OV_ASSERT_NO_THROW(req.start_async());- bool ready = false;- OV_ASSERT_NO_THROW(ready = req.wait_for({}));- // get timestamp taken AFTER return from the wait(STATUS_ONLY)- const auto afterWaitTimeStamp = std::chrono::system_clock::now();- // IF the callback timestamp is larger than the afterWaitTimeStamp- // then we should observe false ready result- if (afterWaitTimeStamp < callbackTimeStampFuture.get()) {- ASSERT_FALSE(ready);- }- OV_ASSERT_NO_THROW(req.wait());-}-TEST_P(OVInferRequestCallbackTestsNPU, ImplDoesNotCopyCallback) {- ov::InferRequest req;- OV_ASSERT_NO_THROW(req = execNet.create_infer_request());- {- auto somePtr = std::make_shared<int>(42);- OV_ASSERT_NO_THROW(req.set_callback([somePtr](std::exception_ptr exception_ptr) {- ASSERT_EQ(nullptr, exception_ptr);- ASSERT_EQ(1, somePtr.use_count());- }));- }OV_ASSERT_NO_THROW(req.start_async());OV_ASSERT_NO_THROW(req.wait());++ ASSERT_EQ(nested_done_future.wait_for(std::chrono::seconds(30)), std::future_status::ready);+ ASSERT_GE(callback_calls.load(std::memory_order_relaxed), 2);}} // namespace behaviordiff --git a/src/tests/functional/base_func_tests/include/behavior/ov_infer_request/callback.hpp b/src/tests/functional/base_func_tests/include/behavior/ov_infer_request/callback.hppindex 30f107ee34f..e2af544a50a 100644--- a/src/tests/functional/base_func_tests/include/behavior/ov_infer_request/callback.hpp+++ b/src/tests/functional/base_func_tests/include/behavior/ov_infer_request/callback.hpp@@ -4,7 +4,12 @@#pragma once+#include <atomic>+#include <chrono>+#include <condition_variable>#include <future>+#include <mutex>+#include <thread>#include "shared_test_classes/base/ov_behavior_test_utils.hpp"@@ -39,9 +44,7 @@ TEST_P(OVInferRequestCallbackTests, syncInferDoesNotCallCompletionCallback) {ASSERT_FALSE(is_called);}-// test that can wait all callbacks on dtor-// Ticket: 151980-TEST_P(OVInferRequestCallbackTests, DISABLED_canStartSeveralAsyncInsideCompletionCallbackWithSafeDtor) {+TEST_P(OVInferRequestCallbackTests, canStartSeveralAsyncInsideCompletionCallbackWithSafeDtor) {const int NUM_ITER = 10;struct TestUserData {std::atomic<int> numIter = {0};@@ -65,7 +68,8 @@ TEST_P(OVInferRequestCallbackTests, DISABLED_canStartSeveralAsyncInsideCompletioauto future = data.promise.get_future();OV_ASSERT_NO_THROW(req.start_async());OV_ASSERT_NO_THROW(req.wait());- future.wait();+ ASSERT_EQ(future.wait_for(std::chrono::seconds(30)), std::future_status::ready)+ << "Timed out waiting for callback completion";auto callbackStatus = future.get();ASSERT_TRUE(callbackStatus);auto dataNumIter = data.numIter - 1;@@ -122,6 +126,66 @@ TEST_P(OVInferRequestCallbackTests, ImplDoesNotCopyCallback) {OV_ASSERT_NO_THROW(req.wait());}+TEST_P(OVInferRequestCallbackTests, CallbackStartsNextInferWithSleepWithoutMissingCallbacks) {+ ov::InferRequest req;+ OV_ASSERT_NO_THROW(req = execNet.create_infer_request());+ OV_ASSERT_NO_THROW(req.get_input_tensor());++ constexpr size_t callback_iterations = 10;+ constexpr auto callback_sleep = std::chrono::milliseconds(50);+ constexpr auto test_timeout = std::chrono::seconds(30);++ std::atomic<size_t> checkout_count{0};+ std::atomic<size_t> callback_count{0};+ std::atomic<size_t> callback_start_failures{0};+ std::atomic<size_t> callback_exception_count{0};++ std::mutex done_mutex;+ std::condition_variable done_cv;+ bool done = false;++ OV_ASSERT_NO_THROW(req.set_callback([&](std::exception_ptr ex) {+ if (ex != nullptr) {+ callback_exception_count.fetch_add(1, std::memory_order_relaxed);+ }++ const auto current_callback = callback_count.fetch_add(1, std::memory_order_relaxed) + 1;++ if (current_callback < callback_iterations) {+ try {+ checkout_count.fetch_add(1, std::memory_order_relaxed);+ req.start_async();+ std::this_thread::sleep_for(callback_sleep);+ } catch (...) {+ callback_start_failures.fetch_add(1, std::memory_order_relaxed);+ std::lock_guard<std::mutex> lock(done_mutex);+ done = true;+ done_cv.notify_one();+ }+ } else {+ std::lock_guard<std::mutex> lock(done_mutex);+ done = true;+ done_cv.notify_one();+ }+ }));++ checkout_count.fetch_add(1, std::memory_order_relaxed);+ OV_ASSERT_NO_THROW(req.start_async());++ {+ std::unique_lock<std::mutex> lock(done_mutex);+ ASSERT_TRUE(done_cv.wait_for(lock, test_timeout, [&]() {+ return done;+ }));+ }++ OV_ASSERT_NO_THROW(req.wait());+ EXPECT_EQ(callback_start_failures.load(std::memory_order_relaxed), 0);+ EXPECT_EQ(callback_exception_count.load(std::memory_order_relaxed), 0);+ EXPECT_EQ(checkout_count.load(std::memory_order_relaxed), callback_iterations);+ EXPECT_EQ(callback_count.load(std::memory_order_relaxed), callback_iterations);+}+} // namespace behavior} // namespace test} // namespace ov