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
[PyOV] Performance improvement for free-threaded python (#31311)
Anastasia Kuporosovab7a0a7ab6484
diff --git a/src/bindings/python/src/openvino/opset9/ops.py b/src/bindings/python/src/openvino/opset9/ops.pyindex 6b3bbb1bc2d..249ca9ebc09 100644--- a/src/bindings/python/src/openvino/opset9/ops.py+++ b/src/bindings/python/src/openvino/opset9/ops.py@@ -117,11 +117,11 @@ def roi_align(:param sampling_ratio: Number of bins over height and width to use to calculateeach output feature map element.:param spatial_scale: Multiplicative spatial scale factor to translate ROI coordinates.- :param mode: Method to perform pooling to produce output feature map elements. Avaiable modes are:+ :param mode: Method to perform pooling to produce output feature map elements. Available modes are:- 'max' - maximum pooling- 'avg' - average pooling:param aligned_mode: Specifies how to transform the coordinate in original tensor to the resized tensor.- Mode 'asymmetric' is the default value. Optional. Avaiable aligned modes are:+ Mode 'asymmetric' is the default value. Optional. Available aligned modes are:- 'asymmetric'- 'half_pixel_for_nn'- 'half_pixel'diff --git a/src/bindings/python/src/pyopenvino/core/async_infer_queue.cpp b/src/bindings/python/src/pyopenvino/core/async_infer_queue.cppindex eea9a00ab77..ef5a5027f3d 100644--- a/src/bindings/python/src/pyopenvino/core/async_infer_queue.cpp+++ b/src/bindings/python/src/pyopenvino/core/async_infer_queue.cpp@@ -46,7 +46,7 @@ public:bool _is_ready() {// Check if any request has finished already- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;// acquire the mutex to access m_errors and m_idle_handlesstd::lock_guard<std::mutex> lock(m_mutex);if (m_errors.size() > 0)@@ -57,7 +57,7 @@ public:size_t get_idle_request_id() {// Wait for any request to complete and return its id// release GIL to avoid deadlock on python callback- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;// acquire the mutex to access m_errors and m_idle_handlesstd::unique_lock<std::mutex> lock(m_mutex);m_cv.wait(lock, [this] {@@ -74,7 +74,7 @@ public:void wait_all() {// Wait for all request to complete// release GIL to avoid deadlock on python callback- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;for (auto&& request : m_requests) {request.m_request->wait();}@@ -119,7 +119,7 @@ public:*m_requests[handle].m_end_time = Time::now();if (exception_ptr == nullptr) {// Acquire GIL, execute Python function- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;try {(*callback_sp)(m_requests[handle], m_user_ids[handle]);} catch (const py::error_already_set& py_error) {@@ -200,7 +200,7 @@ void regclass_AsyncInferQueue(py::module m) {self.m_requests[handle].m_request->set_input_tensor(inputs);// Now GIL can be released - we are NOT working with Python objects in this block{- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;*self.m_requests[handle].m_start_time = Time::now();// Start InferRequest in asynchronus modeself.m_requests[handle].m_request->start_async();@@ -246,7 +246,7 @@ void regclass_AsyncInferQueue(py::module m) {Common::set_request_tensors(*self.m_requests[handle].m_request, inputs);// Now GIL can be released - we are NOT working with Python objects in this block{- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;*self.m_requests[handle].m_start_time = Time::now();// Start InferRequest in asynchronus modeself.m_requests[handle].m_request->start_async();@@ -328,7 +328,7 @@ void regclass_AsyncInferQueue(py::module m) {},R"(Number of InferRequests in the pool.-+:rtype: int)");diff --git a/src/bindings/python/src/pyopenvino/core/common.cpp b/src/bindings/python/src/pyopenvino/core/common.cppindex 117ed60308b..b20e74ef3ec 100644--- a/src/bindings/python/src/pyopenvino/core/common.cpp+++ b/src/bindings/python/src/pyopenvino/core/common.cpp@@ -10,6 +10,7 @@#include "openvino/core/except.hpp"#include "openvino/util/common_util.hpp"#include "pyopenvino/core/remote_tensor.hpp"+#include "pyopenvino/utils/utils.hpp"#define C_CONTIGUOUS py::detail::npy_api::constants::NPY_ARRAY_C_CONTIGUOUS_@@ -418,7 +419,7 @@ std::shared_ptr<ov::SharedBuffer<py::array>> get_shared_memory(py::array& array)array.ndim() == 0 ? array.itemsize() : array.nbytes(),array);std::shared_ptr<ov::SharedBuffer<py::array>> memory(buffer, [](ov::SharedBuffer<py::array>* buffer) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;delete buffer;});return memory;diff --git a/src/bindings/python/src/pyopenvino/core/compiled_model.cpp b/src/bindings/python/src/pyopenvino/core/compiled_model.cppindex 63baa42b306..e17bfb2ecb0 100644--- a/src/bindings/python/src/pyopenvino/core/compiled_model.cpp+++ b/src/bindings/python/src/pyopenvino/core/compiled_model.cpp@@ -30,7 +30,7 @@ void regclass_CompiledModel(py::module m) {// Create temporary ov::InferRequest and move it to actual wrapper class.ov::InferRequest request;{- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;request = self.create_infer_request();}return std::make_shared<InferRequestWrapper>(std::move(request), self.inputs(), self.outputs());@@ -171,7 +171,7 @@ void regclass_CompiledModel(py::module m) {cls.def("get_runtime_model",&ov::CompiledModel::get_runtime_model,- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Gets runtime model information from a device.@@ -186,7 +186,7 @@ void regclass_CompiledModel(py::module m) {cls.def("release_memory",&ov::CompiledModel::release_memory,- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Release intermediate memory.diff --git a/src/bindings/python/src/pyopenvino/core/core.cpp b/src/bindings/python/src/pyopenvino/core/core.cppindex c5b23bab5fe..4d3e2f3b298 100644--- a/src/bindings/python/src/pyopenvino/core/core.cpp+++ b/src/bindings/python/src/pyopenvino/core/core.cpp@@ -156,7 +156,7 @@ void regclass_Core(py::module m) {const std::string& device_name,const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.compile_model(model, device_name, _properties);},py::arg("model"),@@ -185,7 +185,7 @@ void regclass_Core(py::module m) {const std::shared_ptr<const ov::Model>& model,const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.compile_model(model, _properties);},py::arg("model"),@@ -213,7 +213,7 @@ void regclass_Core(py::module m) {const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);std::string path = Common::utils::convert_path_to_string(model_path);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.compile_model(path, device_name, _properties);},py::arg("model_path"),@@ -258,7 +258,7 @@ void regclass_Core(py::module m) {tensor = ov::Tensor(ov::element::Type_t::u8, {bin_size});}auto _properties = Common::utils::properties_to_any_map(properties);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.compile_model(model.cast<std::string>(), tensor, device_name, _properties);},py::arg("model_buffer"),@@ -289,7 +289,7 @@ void regclass_Core(py::module m) {[](ov::Core& self, const py::object& model_path, const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);std::string path = Common::utils::convert_path_to_string(model_path);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.compile_model(path, _properties);},py::arg("model_path"),@@ -316,7 +316,7 @@ void regclass_Core(py::module m) {const RemoteContextWrapper& context,const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.compile_model(model, context.context, _properties);},py::arg("model"),@@ -397,7 +397,7 @@ void regclass_Core(py::module m) {const uint8_t* bin = reinterpret_cast<const uint8_t*>(info.ptr);std::memcpy(tensor.data(), bin, bin_size);}- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.read_model(ir, tensor);},py::arg("model"),@@ -422,7 +422,7 @@ void regclass_Core(py::module m) {const std::string& weight_path,const std::map<std::string, py::object>& config) {const auto any_map = Common::utils::properties_to_any_map(config);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.read_model(model_path, weight_path, any_map);},py::arg("model"),@@ -452,7 +452,7 @@ void regclass_Core(py::module m) {cls.def("read_model",(std::shared_ptr<ov::Model>(ov::Core::*)(const std::string&, const ov::Tensor&) const) & ov::Core::read_model,- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),py::arg("model"),py::arg("weights"),R"(@@ -491,7 +491,7 @@ void regclass_Core(py::module m) {const uint8_t* bin = reinterpret_cast<const uint8_t*>(info.ptr);std::memcpy(tensor.data(), bin, bin_size);}- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.read_model(std::string(static_cast<char*>(buffer_info.ptr), buffer_info.size), tensor);} else if (py::isinstance(model_path, py::module_::import("pathlib").attr("Path")) ||py::isinstance<py::str>(model_path)) {@@ -501,7 +501,7 @@ void regclass_Core(py::module m) {weights_path_cpp = py::str(weights_path);}const auto any_map = Common::utils::properties_to_any_map(config);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.read_model(model_path_cpp, weights_path_cpp, any_map);}@@ -557,7 +557,7 @@ void regclass_Core(py::module m) {Common::utils::MemoryBuffer mb(reinterpret_cast<char*>(info.ptr), info.size);std::istream stream(&mb);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.import_model(stream, device_name, _properties);},py::arg("model_stream"),@@ -671,7 +671,7 @@ void regclass_Core(py::module m) {const std::string& device_name,const std::map<std::string, py::object>& properties) -> std::map<std::string, std::string> {auto _properties = Common::utils::properties_to_any_map(properties);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.query_model(model, device_name, _properties);},py::arg("model"),@@ -738,7 +738,7 @@ void regclass_Core(py::module m) {cls.def("get_available_devices",&ov::Core::get_available_devices,- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Returns devices available for inference Core objects goes over all registered plugins.@@ -753,7 +753,7 @@ void regclass_Core(py::module m) {cls.def_property_readonly("available_devices",&ov::Core::get_available_devices,- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Returns devices available for inference Core objects goes over all registered plugins.diff --git a/src/bindings/python/src/pyopenvino/core/infer_request.cpp b/src/bindings/python/src/pyopenvino/core/infer_request.cppindex 2f99ff875b6..39650d18d81 100644--- a/src/bindings/python/src/pyopenvino/core/infer_request.cpp+++ b/src/bindings/python/src/pyopenvino/core/infer_request.cpp@@ -17,7 +17,7 @@ namespace py = pybind11;inline py::object run_sync_infer(InferRequestWrapper& self, bool share_outputs, bool decode_strings) {{- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;*self.m_start_time = Time::now();self.m_request->infer();*self.m_end_time = Time::now();@@ -231,7 +231,7 @@ void regclass_InferRequest(py::module m) {PyErr_WarnEx(PyExc_RuntimeWarning, "There is no callback function to pass `userdata` into!", 1);}}- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;*self.m_start_time = Time::now();self.m_request->start_async();},@@ -270,7 +270,7 @@ void regclass_InferRequest(py::module m) {PyErr_WarnEx(PyExc_RuntimeWarning, "There is no callback function!", 1);}}- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;*self.m_start_time = Time::now();self.m_request->start_async();},@@ -303,11 +303,11 @@ void regclass_InferRequest(py::module m) {cls.def("wait",[](InferRequestWrapper& self) {- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;self.m_request->wait();},R"(- Waits for the result to become available.+ Waits for the result to become available.Blocks until the result becomes available.GIL is released while running this function.@@ -316,7 +316,7 @@ void regclass_InferRequest(py::module m) {cls.def("wait_for",[](InferRequestWrapper& self, const int timeout) {- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return self.m_request->wait_for(std::chrono::milliseconds(timeout));},py::arg("timeout"),@@ -352,7 +352,7 @@ void regclass_InferRequest(py::module m) {OPENVINO_THROW("Caught exception: ", e.what());}// Acquire GIL, execute Python function- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;(*callback_sp)(self.m_userdata);});},@@ -609,7 +609,7 @@ void regclass_InferRequest(py::module m) {[](InferRequestWrapper& self) {return self.m_request->get_profiling_info();},- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Queries performance is measured per layer to get feedback on whatis the most time-consuming operation, not all plugins provide@@ -626,7 +626,7 @@ void regclass_InferRequest(py::module m) {[](InferRequestWrapper& self) {return self.m_request->query_state();},- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Gets state control interface for given infer request.@@ -715,7 +715,7 @@ void regclass_InferRequest(py::module m) {},R"(Gets latency of this InferRequest.-+:rtype: float)");@@ -724,7 +724,7 @@ void regclass_InferRequest(py::module m) {[](InferRequestWrapper& self) {return self.m_request->get_profiling_info();},- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),R"(Performance is measured per layer to get feedback on the most time-consuming operation.Not all plugins provide meaningful data!diff --git a/src/bindings/python/src/pyopenvino/core/remote_context.cpp b/src/bindings/python/src/pyopenvino/core/remote_context.cppindex 8e2ff5482c2..7638fd6d8ef 100644--- a/src/bindings/python/src/pyopenvino/core/remote_context.cpp+++ b/src/bindings/python/src/pyopenvino/core/remote_context.cpp@@ -51,7 +51,7 @@ void regclass_RemoteContext(py::module m) {const ov::Shape& shape,const std::map<std::string, py::object>& properties) {auto _properties = Common::utils::properties_to_any_map(properties);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;return RemoteTensorWrapper(self.context.create_tensor(type, shape, _properties));},py::arg("type"),@@ -79,7 +79,7 @@ void regclass_RemoteContext(py::module m) {[](RemoteContextWrapper& self, const ov::element::Type& type, const ov::Shape& shape) {return self.context.create_host_tensor(type, shape);},- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),py::arg("type"),py::arg("shape"),R"(@@ -132,7 +132,7 @@ void regclass_VAContext(py::module m) {[](VAContextWrapper& self, const size_t height, const size_t width, const uint32_t nv12_surface) {ov::RemoteTensor y_tensor, uv_tensor;{- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;ov::AnyMap tensor_params = {{ov::intel_gpu::shared_mem_type.name(), ov::intel_gpu::SharedMemType::VA_SURFACE},{ov::intel_gpu::dev_object_handle.name(), nv12_surface},@@ -174,7 +174,7 @@ void regclass_VAContext(py::module m) {{ov::intel_gpu::va_plane.name(), plane}};return VASurfaceTensorWrapper(self.context.create_tensor(type, shape, params));},- py::call_guard<py::gil_scoped_release>(),+ CallGuardConditionalGILRelease(),py::arg("type"),py::arg("shape"),py::arg("surface"),diff --git a/src/bindings/python/src/pyopenvino/frontend/extension.cpp b/src/bindings/python/src/pyopenvino/frontend/extension.cppindex 69c0453ae93..ce965c14bc5 100644--- a/src/bindings/python/src/pyopenvino/frontend/extension.cpp+++ b/src/bindings/python/src/pyopenvino/frontend/extension.cpp@@ -40,15 +40,15 @@ void regclass_frontend_TelemetryExtension(py::module m) {const std::string& action,const std::string& label,int value) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;(*send_event_sp)(category, action, label, value);},[send_error_sp](const std::string& category, const std::string& error_message) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;(*send_error_sp)(category, error_message);},[send_stack_trace_sp](const std::string& category, const std::string& error_message) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;(*send_stack_trace_sp)(category, error_message);});}));@@ -125,7 +125,7 @@ void regclass_frontend_ProgressReporterExtension(py::module m) {ext.def(py::init([](py::function& callback) {return std::make_shared<ProgressReporterExtension>([callback](float a, unsigned int b, unsigned int c) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;callback(a, b, c);});}));diff --git a/src/bindings/python/src/pyopenvino/graph/model.cpp b/src/bindings/python/src/pyopenvino/graph/model.cppindex 89c637b2c15..35c6f20da18 100644--- a/src/bindings/python/src/pyopenvino/graph/model.cpp+++ b/src/bindings/python/src/pyopenvino/graph/model.cpp@@ -492,7 +492,7 @@ void regclass_graph_Model(py::module m) {"reshape",[](ov::Model& self, const ov::PartialShape& partial_shape, const py::dict& variables_shapes) {const auto new_variable_shapes = get_variables_shapes(variables_shapes);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;self.reshape(partial_shape, new_variable_shapes);},py::arg("partial_shape"),@@ -534,7 +534,7 @@ void regclass_graph_Model(py::module m) {[](ov::Model& self, const py::list& partial_shape, const py::dict& variables_shapes) {const auto new_shape = Common::partial_shape_from_list(partial_shape);const auto new_variables_shapes = get_variables_shapes(variables_shapes);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;self.reshape(new_shape, new_variables_shapes);},py::arg("partial_shape"),@@ -576,7 +576,7 @@ void regclass_graph_Model(py::module m) {[](ov::Model& self, const py::tuple& partial_shape, const py::dict& variables_shapes) {const auto new_shape = Common::partial_shape_from_list(partial_shape.cast<py::list>());const auto new_variables_shapes = get_variables_shapes(variables_shapes);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;self.reshape(new_shape, new_variables_shapes);},py::arg("partial_shape"),@@ -617,7 +617,7 @@ void regclass_graph_Model(py::module m) {"reshape",[](ov::Model& self, const std::string& partial_shape, const py::dict& variables_shapes) {const auto new_variables_shape = get_variables_shapes(variables_shapes);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;self.reshape(ov::PartialShape(partial_shape), new_variables_shape);},py::arg("partial_shape"),@@ -665,7 +665,7 @@ void regclass_graph_Model(py::module m) {partial_shape_from_handle(item.second));}const auto new_variables_shapes = get_variables_shapes(variables_shapes);- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;self.reshape(new_shapes, new_variables_shapes);},py::arg("partial_shapes"),@@ -1121,7 +1121,7 @@ void regclass_graph_Model(py::module m) {&ov::Model::remove_parameter,py::arg("parameter"),R"(- Delete Parameter node from the list of parameters. Method will not delete node from graph.+ Delete Parameter node from the list of parameters. Method will not delete node from graph.You need to replace Parameter with other operation manually.Attention: Indexing of parameters can be changed.@@ -1190,7 +1190,7 @@ void regclass_graph_Model(py::module m) {py::arg("results"),R"(Add new Result nodes to the list.-+Method doesn't validate graph, it should be done manually after all changes.:param results: new Result nodes.@@ -1212,7 +1212,7 @@ void regclass_graph_Model(py::module m) {py::arg("sinks"),R"(Add new sink nodes to the list.-+Method doesn't validate graph, it should be done manually after all changes.:param sinks: new sink nodes.@@ -1223,8 +1223,8 @@ void regclass_graph_Model(py::module m) {&ov::Model::add_variables,py::arg("variables"),R"(- Add new variables to the list.-+ Add new variables to the list.+Method doesn't validate graph, it should be done manually after all changes.:param variables: new variables to add.@@ -1253,7 +1253,7 @@ void regclass_graph_Model(py::module m) {&ov::Model::get_variable_by_id,R"(Return a variable by specified variable_id.-+:param variable_id: a variable id to get variable node.:type variable_id: str:return: a variable node.@@ -1448,7 +1448,7 @@ void regclass_graph_Model(py::module m) {},R"(Returns a raw address of the Model object from C++.-+Use this function in order to compare underlying C++ addresses instead of using `__eq__` in Python.:return: a raw address of the Model object.diff --git a/src/bindings/python/src/pyopenvino/graph/op.cpp b/src/bindings/python/src/pyopenvino/graph/op.cppindex 27fa98e06e8..37c9dae233e 100644--- a/src/bindings/python/src/pyopenvino/graph/op.cpp+++ b/src/bindings/python/src/pyopenvino/graph/op.cpp@@ -13,6 +13,7 @@#include "openvino/core/attribute_visitor.hpp"#include "openvino/core/node.hpp"+#include "pyopenvino/utils/utils.hpp"namespace py = pybind11;@@ -21,7 +22,7 @@ void PyOp::validate_and_infer_types() {}bool PyOp::visit_attributes(ov::AttributeVisitor& value) {- py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.+ ConditionalGILScopedAcquire gil; // Acquire the GIL while in this scope.// Try to look up the overridden method on the Python side.py::function overrided_py_method = pybind11::get_override(this, "visit_attributes");if (overrided_py_method) { // method is found@@ -31,7 +32,7 @@ bool PyOp::visit_attributes(ov::AttributeVisitor& value) {}std::shared_ptr<ov::Node> PyOp::clone_with_new_inputs(const ov::OutputVector& new_args) const {- py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.+ ConditionalGILScopedAcquire gil; // Acquire the GIL while in this scope.// Try to look up the overridden method on the Python side.py::function overrided_py_method = pybind11::get_override(this, "clone_with_new_inputs");if (overrided_py_method) { // method is found@@ -53,7 +54,7 @@ bool PyOp::evaluate(ov::TensorVector& output_values, const ov::TensorVector& inp}bool PyOp::has_evaluate() const {- py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.+ ConditionalGILScopedAcquire gil; // Acquire the GIL while in this scope.// Try to look up the overridden method on the Python side.py::function overrided_py_method = pybind11::get_override(this, "has_evaluate");if (overrided_py_method) { // method is found@@ -67,7 +68,7 @@ bool PyOp::has_evaluate() const {}void PyOp::update_type_info() {- py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.+ ConditionalGILScopedAcquire gil; // Acquire the GIL while in this scope.// Try to look up the overridden method on the Python side.py::function overriden_py_method = pybind11::get_override(this, "get_type_info");diff --git a/src/bindings/python/src/pyopenvino/graph/op_extension.cpp b/src/bindings/python/src/pyopenvino/graph/op_extension.cppindex 70834f31326..3b459833143 100644--- a/src/bindings/python/src/pyopenvino/graph/op_extension.cpp+++ b/src/bindings/python/src/pyopenvino/graph/op_extension.cpp@@ -2,17 +2,16 @@// SPDX-License-Identifier: Apache-2.0//-#include "openvino/core/op_extension.hpp"+#include "pyopenvino/graph/op_extension.hpp"#include <pybind11/pybind11.h>-#include <pyopenvino/graph/op_extension.hpp>-#include "pyopenvino/core/common.hpp"#include "pyopenvino/core/extension.hpp"#include "pyopenvino/graph/discrete_type_info.hpp"#include "pyopenvino/graph/node_output.hpp"#include "pyopenvino/graph/op.hpp"+#include "pyopenvino/utils/utils.hpp"namespace py = pybind11;@@ -21,7 +20,7 @@ const ov::DiscreteTypeInfo& PyOpExtension::get_type_info() const {}ov::OutputVector PyOpExtension::create(const ov::OutputVector& inputs, ov::AttributeVisitor& visitor) const {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;const auto node = py_handle_dtype();diff --git a/src/bindings/python/src/pyopenvino/graph/preprocess/pre_post_process.cpp b/src/bindings/python/src/pyopenvino/graph/preprocess/pre_post_process.cppindex eb9e3eac65e..c56fe69f8f5 100644--- a/src/bindings/python/src/pyopenvino/graph/preprocess/pre_post_process.cpp+++ b/src/bindings/python/src/pyopenvino/graph/preprocess/pre_post_process.cpp@@ -5,8 +5,11 @@#include "pyopenvino/graph/preprocess/pre_post_process.hpp"#include <pybind11/functional.h>+#include <pybind11/pybind11.h>#include <pybind11/stl.h>+#include <sstream>+#include "openvino/core/model.hpp"#include "openvino/core/node.hpp"#include "openvino/core/preprocess/pre_post_process.hpp"@@ -191,7 +194,7 @@ static void regclass_graph_PreProcessSteps(py::module m) {:type pads_begin: 1D tensor of type T_INT.:param pads_end: Number of elements matches the number of indices in data attribute. Specifies the number of padding elements at the ending of each axis.:type pads_end: 1D tensor of type T_INT.- :param value: All new elements are populated with this value or with 0 if input not provided. Shouldn’t be set for other pad_mode values.+ :param value: All new elements are populated with this value or with 0 if input not provided. Shouldn't be set for other pad_mode values.:type value: scalar tensor of type T.:param mode: pad_mode specifies the method used to generate new element values.:type mode: string@@ -219,7 +222,7 @@ static void regclass_graph_PreProcessSteps(py::module m) {:type pads_begin: 1D tensor of type T_INT.:param pads_end: Number of elements matches the number of indices in data attribute. Specifies the number of padding elements at the ending of each axis.:type pads_end: 1D tensor of type T_INT.- :param value: All new elements are populated with this value or with 0 if input not provided. Shouldn’t be set for other pad_mode values.+ :param value: All new elements are populated with this value or with 0 if input not provided. Shouldn't be set for other pad_mode values.:type value: scalar tensor of type T.:param mode: pad_mode specifies the method used to generate new element values.:type mode: string@@ -368,7 +371,7 @@ static void regclass_graph_InputTensorInfo(py::module m) {R"(Helper function to reuse element type and shape from user's created tensor. Overwrites previouslyset shape and element type via `set_shape` and `set_element_type' methods. This method should be- used only in case if tensor is already known and avaiable before.+ used only in case if tensor is already known and available before.:param tensor: User's created tensor:type type: openvino.Tensor@@ -386,7 +389,7 @@ static void regclass_graph_InputTensorInfo(py::module m) {R"(Helper function to reuse element type and shape from user's created tensor. Overwrites previouslyset shape and element type via `set_shape` and `set_element_type' methods. This method should be- used only in case if tensor is already known and avaiable before.+ used only in case if tensor is already known and available before.:param tensor: User's created numpy array:type type: numpy.ndarray@@ -602,7 +605,7 @@ void regclass_graph_PrePostProcessor(py::module m) {proc.def("build", [](ov::preprocess::PrePostProcessor& self) {std::shared_ptr<ov::Model> model;{- py::gil_scoped_release release;+ ConditionalGILScopedRelease release;model = self.build();}py::type model_class = py::module_::import("openvino").attr("Model");diff --git a/src/bindings/python/src/pyopenvino/utils/utils.cpp b/src/bindings/python/src/pyopenvino/utils/utils.cppindex 2b0deba8535..dde59a79a80 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.cpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.cpp@@ -296,26 +296,26 @@ std::map<std::string, ov::Any> properties_to_any_map(const std::map<std::string,// Wrapped to sp due-to we need to hold GIL upon destruction of python functionauto py_encrypt = std::shared_ptr<py::function>(new py::function(std::move(property_list[0])),[](py::function* py_encrypt) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;delete py_encrypt;});auto py_decrypt = std::shared_ptr<py::function>(new py::function(std::move(property_list[1])),[](py::function* py_decrypt) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;delete py_decrypt;});std::function<std::string(const std::string&)> encrypt_func =[py_encrypt](const std::string& in_str) -> std::string {// Acquire GIL, execute Python function- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;return (*py_encrypt)(py::bytes(in_str)).cast<std::string>();};std::function<std::string(const std::string&)> decrypt_func =[py_decrypt](const std::string& in_str) -> std::string {// Acquire GIL, execute Python function- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;return (*py_decrypt)(py::bytes(in_str)).cast<std::string>();};ov::EncryptionCallbacks encryption_callbacks{encrypt_func, decrypt_func};@@ -576,7 +576,7 @@ ov::Any py_object_to_any(const py::object& py_obj) {// If there is no match fallback to py::object} else if (py::isinstance<py::object>(py_obj)) {return std::shared_ptr<py::object>(new py::object(py_obj), [](py::object* py_obj_reference) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;delete py_obj_reference;});}@@ -584,7 +584,7 @@ ov::Any py_object_to_any(const py::object& py_obj) {}std::shared_ptr<py::function> wrap_pyfunction(py::function f_callback) {auto callback_sp = std::shared_ptr<py::function>(new py::function(std::move(f_callback)), [](py::function* c) {- py::gil_scoped_acquire acquire;+ ConditionalGILScopedAcquire acquire;delete c;});return callback_sp;diff --git a/src/bindings/python/src/pyopenvino/utils/utils.hpp b/src/bindings/python/src/pyopenvino/utils/utils.hppindex 8cf2c459e3c..f28a4faa8c0 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.hpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.hpp@@ -7,6 +7,7 @@#include <pybind11/pybind11.h>#include <filesystem>+#include <variant>#ifdef _MSC_VER// Warning occurred at the junction of pybind11@@ -32,6 +33,21 @@namespace py = pybind11;+// Conditional GIL management for PEP 703 (free-threaded Python)+inline constexpr bool PY_GIL_DISABLED {+#if defined(Py_GIL_DISABLED) && Py_GIL_DISABLED+ true+#else+ false+#endif+};++using ConditionalGILScopedRelease = std::conditional_t<PY_GIL_DISABLED, std::monostate, py::gil_scoped_release>;+using ConditionalGILScopedAcquire = std::conditional_t<PY_GIL_DISABLED, std::monostate, py::gil_scoped_acquire>;++// For free-threaded Python, we don't need call_guard - use empty call_guard+using CallGuardConditionalGILRelease = std::conditional_t<PY_GIL_DISABLED, py::call_guard<>, py::call_guard<py::gil_scoped_release>>;+namespace Common {namespace utils {diff --git a/src/bindings/python/tests/test_graph/test_custom_op.py b/src/bindings/python/tests/test_graph/test_custom_op.pyindex 4f8f36ae4c1..9d80c34e3bf 100644--- a/src/bindings/python/tests/test_graph/test_custom_op.py+++ b/src/bindings/python/tests/test_graph/test_custom_op.py@@ -146,7 +146,6 @@ def test_visit_attributes_custom_op(device, prepared_paths, attributes, expectatcustom = CustomOpWithAttribute(inputs=[param1, param2], attrs=attributes)res = ops.result(custom, name="result")model_with_op_attr = Model(res, [param1, param2], "CustomModel")-xml_path, bin_path = prepared_pathswith expectation as e:@@ -163,7 +162,6 @@ def test_visit_attributes_custom_op(device, prepared_paths, attributes, expectatinput_data = np.ones([2, 1], dtype=np.float32)expected_output = np.maximum(0.0, input_data)-compiled_model = compile_model(model_with_op_attr, device)input_tensor = Tensor(input_data)results = compiled_model({"data1": input_tensor})