Skip to content

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

[PyOV] Pass GPU handles from Python to create_context and create_tensor (#39511)

Łukasz Ślusarczyk65dd59b617ab
diff --git a/src/bindings/python/src/pyopenvino/utils/utils.cpp b/src/bindings/python/src/pyopenvino/utils/utils.cpp
index 3e01248ac1c..ea69d13aeb5 100644
--- a/src/bindings/python/src/pyopenvino/utils/utils.cpp
+++ b/src/bindings/python/src/pyopenvino/utils/utils.cpp
@@ -8,10 +8,12 @@
#include <pybind11/stl/filesystem.h>
#include <cmath>
+#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <tuple>
+#include <type_traits>
#include <vector>
#include "Python.h"
@@ -20,6 +22,7 @@
#include "openvino/frontend/decoder.hpp"
#include "openvino/frontend/graph_iterator.hpp"
#include "openvino/runtime/intel_cpu/properties.hpp"
+#include "openvino/runtime/intel_gpu/remote_properties.hpp"
#include "openvino/runtime/intel_npu/properties.hpp"
#include "openvino/runtime/properties.hpp"
@@ -297,12 +300,55 @@ py::object from_ov_any(const ov::Any& any) {
return py::cast(any.as<ov::frontend::type::PyScalar>());
} else if (any.is<ov::Tensor>()) {
return py::cast(any.as<ov::Tensor>());
+ } else if (any.is<void*>()) {
+ return py::int_(reinterpret_cast<uintptr_t>(any.as<void*>()));
} else {
PyErr_SetString(PyExc_TypeError, "Failed to convert parameter to Python representation!");
return py::cast<py::object>((PyObject*)NULL);
}
}
+template <typename T, ov::PropertyMutability mutability>
+static bool is_pointer(const ov::Property<T, mutability>& property, const std::string& name) {
+ return std::is_same_v<T, void*> && name == property.name();
+}
+
+// ov::intel_gpu::os_handle and ov::intel_gpu::dev_object_handle are void* only on Windows.
+static bool is_pointer_property(const std::string& name) {
+ return is_pointer(ov::intel_gpu::ocl_context, name) || is_pointer(ov::intel_gpu::ocl_queue, name) ||
+ is_pointer(ov::intel_gpu::va_device, name) || is_pointer(ov::intel_gpu::mem_handle, name) ||
+ is_pointer(ov::intel_gpu::cpu_va, name) || is_pointer(ov::intel_gpu::os_handle, name) ||
+ is_pointer(ov::intel_gpu::dev_object_handle, name);
+}
+
+static void* to_pointer(const std::string& name, py::object value) {
+ constexpr auto expected_types = " property should be an int address, ctypes.c_void_p or None";
+ if (py::isinstance<ov::Any>(value)) {
+ value = from_ov_any(value.cast<const ov::Any&>());
+ if (!value) {
+ PyErr_Clear();
+ OPENVINO_THROW("The value of ", name, expected_types);
+ }
+ }
+ if (py::isinstance(value, py::module_::import("ctypes").attr("c_void_p"))) {
+ value = value.attr("value");
+ }
+ if (value.is_none()) {
+ return nullptr;
+ }
+ OPENVINO_ASSERT(!py::isinstance<py::bool_>(value), "The value of ", name, expected_types);
+ const auto index = py::reinterpret_steal<py::object>(PyNumber_Index(value.ptr()));
+ if (!index) {
+ PyErr_Clear();
+ OPENVINO_THROW("The value of ", name, expected_types);
+ }
+ try {
+ return reinterpret_cast<void*>(index.cast<uintptr_t>());
+ } catch (const py::cast_error&) {
+ OPENVINO_THROW("The value of ", name, " property should be an int address in range [0, ", UINTPTR_MAX, "]");
+ }
+}
+
std::map<std::string, ov::Any> properties_to_any_map(const std::map<std::string, py::object>& properties) {
std::map<std::string, ov::Any> properties_to_cpp;
for (const auto& property : properties) {
@@ -370,6 +416,8 @@ std::map<std::string, ov::Any> properties_to_any_map(const std::map<std::string,
} else if (property.first == ov::intel_auto::perf_curve_table.name() &&
py::isinstance<py::dict>(property.second)) {
properties_to_cpp[property.first] = property.second.cast<ov::intel_auto::PerfCurveTable>();
+ } else if (is_pointer_property(property.first)) {
+ properties_to_cpp[property.first] = to_pointer(property.first, property.second);
} else {
properties_to_cpp[property.first] = Common::utils::py_object_to_any(property.second);
}
diff --git a/src/bindings/python/tests/test_runtime/test_remote_api.py b/src/bindings/python/tests/test_runtime/test_remote_api.py
index 62d4654016c..b8b6dcf2c46 100644
--- a/src/bindings/python/tests/test_runtime/test_remote_api.py
+++ b/src/bindings/python/tests/test_runtime/test_remote_api.py
@@ -2,6 +2,8 @@
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
+import ctypes
+import mmap
import os
import pytest
@@ -12,6 +14,13 @@ import openvino as ov
from tests.utils.helpers import get_relu_model
+# The GPU plugin accepts host memory passed as CPU_VA only at an address aligned to GPU_CACHELINE_SIZE.
+# mmap returns memory aligned to a 4 KB page, which is a multiple of any GPU cacheline size.
+def page_aligned_array(shape, dtype):
+ nbytes = int(np.prod(shape)) * np.dtype(dtype).itemsize
+ return np.frombuffer(mmap.mmap(-1, nbytes), dtype=dtype).reshape(shape)
+
+
@pytest.mark.skipif(
"CPU" not in os.environ.get("TEST_DEVICE", ""),
reason="Test can be only performed on CPU device!",
@@ -104,6 +113,134 @@ def test_create_device_tensor_gpu():
assert "This function is not implemented." in str(str_data_error.value)
+ "GPU" not in os.environ.get("TEST_DEVICE", ""),
+ reason="Test can be only performed on GPU device!",
+)
[email protected]("to_address", [int, np.uint64, np.int64, ctypes.c_void_p, ov.OVAny])
+def test_create_tensor_from_host_address_gpu(device, to_address):
+ core = ov.Core()
+ context = core.get_default_context(device)
+ # The GPU plugin also requires CPU_VA_SIZE to be a multiple of GPU_CACHELINE_SIZE.
+ cacheline_size = core.get_property(device, "GPU_CACHELINE_SIZE")
+ expected = np.arange(cacheline_size // 4, dtype=np.float32)
+ buffer = page_aligned_array(expected.shape, np.float32)
+ buffer[:] = expected
+
+ tensor = context.create_tensor(
+ ov.Type.f32,
+ ov.Shape(expected.shape),
+ {"SHARED_MEM_TYPE": "CPU_VA", "CPU_VA": to_address(buffer.ctypes.data), "CPU_VA_SIZE": buffer.nbytes},
+ )
+ result = ov.Tensor(ov.Type.f32, ov.Shape(expected.shape))
+ tensor.copy_to(result)
+
+ assert np.array_equal(result.data, expected)
+
+
+ "GPU" not in os.environ.get("TEST_DEVICE", ""),
+ reason="Test can be only performed on GPU device!",
+)
+def test_create_tensor_from_device_memory_handle_gpu(device):
+ core = ov.Core()
+ context = core.get_default_context(device)
+ owner = context.create_tensor(ov.Type.f32, ov.Shape([16]), {})
+ mem_handle = owner.get_params()["MEM_HANDLE"].value
+
+ alias = context.create_tensor(
+ ov.Type.f32,
+ ov.Shape([16]),
+ {"SHARED_MEM_TYPE": "OCL_BUFFER", "MEM_HANDLE": mem_handle},
+ )
+ expected = np.arange(16, dtype=np.float32)
+ owner.copy_from(ov.Tensor(expected))
+ result = ov.Tensor(ov.Type.f32, ov.Shape([16]))
+ alias.copy_to(result)
+
+ assert np.array_equal(result.data, expected)
+
+
+ "GPU" not in os.environ.get("TEST_DEVICE", ""),
+ reason="Test can be only performed on GPU device!",
+)
[email protected]("address", [True, np.True_, -1, 2**64, 1.0, "4096", ov.OVAny("4096")])
+def test_create_tensor_rejects_invalid_address_gpu(device, address):
+ core = ov.Core()
+ context = core.get_default_context(device)
+
+ with pytest.raises(RuntimeError) as address_error:
+ context.create_tensor(
+ ov.Type.f32,
+ ov.Shape([16]),
+ {"SHARED_MEM_TYPE": "CPU_VA", "CPU_VA": address, "CPU_VA_SIZE": 64},
+ )
+ assert "The value of CPU_VA property should be an int address" in str(address_error.value)
+
+
+ "GPU" not in os.environ.get("TEST_DEVICE", ""),
+ reason="Test can be only performed on GPU device!",
+)
+def test_create_context_with_none_handle_gpu(device):
+ core = ov.Core()
+ with pytest.raises(RuntimeError) as context_error:
+ core.create_context(device, {"CONTEXT_TYPE": "OCL", "OCL_CONTEXT": None})
+ assert "user handle is nullptr!" in str(context_error.value)
+
+
+ "GPU" not in os.environ.get("TEST_DEVICE", ""),
+ reason="Test can be only performed on GPU device!",
+)
+def test_create_context_accepts_ovany_handles_from_get_params_gpu(device):
+ core = ov.Core()
+ default_params = core.get_default_context(device).get_params()
+
+ context = core.create_context(device, default_params)
+
+ assert context.get_params()["OCL_CONTEXT"].value == default_params["OCL_CONTEXT"].value
+
+
+ "GPU" not in os.environ.get("TEST_DEVICE", ""),
+ reason="Test can be only performed on GPU device!",
+)
+def test_infer_in_shared_context_with_user_memory_gpu(device):
+ core = ov.Core()
+ default_params = core.get_default_context(device).get_params()
+ ocl_context = default_params["OCL_CONTEXT"].value
+ ocl_queue = default_params["OCL_QUEUE"].value
+ assert isinstance(ocl_context, int)
+ assert isinstance(ocl_queue, int)
+
+ context = core.create_context(device, {"CONTEXT_TYPE": "OCL", "OCL_CONTEXT": ocl_context, "OCL_QUEUE": ocl_queue})
+ assert context.get_params()["OCL_CONTEXT"].value == ocl_context
+
+ model = get_relu_model()
+ compiled = core.compile_model(model, context, {"INFERENCE_PRECISION_HINT": "f32"})
+ shape = list(model.input().shape)
+ input_data = page_aligned_array(shape, np.float32)
+ input_data[:] = np.random.uniform(-1, 1, shape)
+ output_data = page_aligned_array(shape, np.float32)
+
+ def wrap(array):
+ return context.create_tensor(
+ ov.Type.f32,
+ ov.Shape(shape),
+ {"SHARED_MEM_TYPE": "CPU_VA", "CPU_VA": array.ctypes.data, "CPU_VA_SIZE": array.nbytes},
+ )
+
+ request = compiled.create_infer_request()
+ request.set_tensor(compiled.input().get_any_name(), wrap(input_data))
+ request.set_tensor(compiled.output().get_any_name(), wrap(output_data))
+ request.start_async()
+ request.wait()
+
+ assert np.array_equal(output_data, np.maximum(input_data, 0))
+
+
@pytest.mark.skipif(
"GPU" not in os.environ.get("TEST_DEVICE", ""),
reason="Test can be only performed on GPU device!",