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] Fix creation of Constant from numpy string arrays (#38942)
Oke Iyanuoluwa Enochf58d8bbfe82c
diff --git a/src/bindings/python/src/pyopenvino/core/common.cpp b/src/bindings/python/src/pyopenvino/core/common.cppindex 68967712e77..a543494758d 100644--- a/src/bindings/python/src/pyopenvino/core/common.cpp+++ b/src/bindings/python/src/pyopenvino/core/common.cpp@@ -212,13 +212,20 @@ void fill_tensor_from_strings(ov::Tensor& tensor, py::array& array) {for (auto a_first = reinterpret_cast<const uint8_t*>(buf.ptr), a_last = a_first + array.nbytes(); a_first < a_last;a_first += array.itemsize(), ++data) {// TODO: check other unicode kinds? 2BYTE and 1BYTE?- auto _unicode_obj = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, a_first, array.itemsize() / 4);+ auto unicode_obj = py::reinterpret_steal<py::object>(+ PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, a_first, array.itemsize() / 4));+ if (!unicode_obj) {+ throw py::error_already_set();+ }Py_ssize_t utf8_size = 0;- const auto utf8_str = PyUnicode_AsUTF8AndSize(_unicode_obj, &utf8_size);+ const auto utf8_str = PyUnicode_AsUTF8AndSize(unicode_obj.ptr(), &utf8_size);+ // Strings which cannot be encoded to UTF-8 (e.g. lone surrogates) raise UnicodeEncodeError.+ if (!utf8_str) {+ throw py::error_already_set();+ }*data = std::string(utf8_str, find_last_not_null(utf8_str, utf8_size));- Py_XDECREF(_unicode_obj);}}@@ -290,6 +297,12 @@ py::array as_contiguous(py::array& array, ov::element::Type type) {case ov::element::f16:case ov::element::bf16:return array.view("int16").cast<py::array_t<int16_t, py::array::c_style | py::array::forcecast>>();+ // fixed-width strings keep their numpy dtype+ case ov::element::string: {+ py::array result = py::array::ensure(array, py::array::c_style);+ OPENVINO_ASSERT(result, "Failed to ensure a contiguous NumPy array for string tensor.");+ return result;+ }default:OPENVINO_THROW("Tensor cannot be created as contiguous!");}@@ -459,6 +472,13 @@ ov::op::v0::Constant create_copied(py::array& array) {if (!array_helpers::is_contiguous(array)) {array = array_helpers::as_contiguous(array, type);}+ // Special case with string data type of kind "S"(bytes_) or "U"(str_).+ // Numpy stores fixed-width characters, so they have to be converted to std::string elements first.+ if (type == ov::element::string) {+ auto tensor = ov::Tensor(ov::element::string, array_helpers::get_shape(array));+ string_helpers::fill_string_tensor_data(tensor, array);+ return ov::op::v0::Constant(tensor);+ }// Create actual Constant and a constructor is copying data.// If ndim is equal to 0, creates scalar Constant.// If size is equal to 0, creates empty Constant.@@ -475,6 +495,8 @@ ov::op::v0::Constant create_copied(ov::Tensor& tensor) {template <>ov::op::v0::Constant create_shared(py::array& array) {+ OPENVINO_ASSERT(type_helpers::get_ov_type(array) != ov::element::string,+ "SHARED MEMORY MODE FOR THIS CONSTANT IS NOT APPLICABLE! String types can be only copied.");return ov::op::v0::Constant(type_helpers::get_ov_type(array),array_helpers::get_shape(array),constant_helpers::get_shared_memory(array));diff --git a/src/bindings/python/tests/test_graph/test_constant.py b/src/bindings/python/tests/test_graph/test_constant.pyindex 59da1245f4d..7f54e44fe94 100644--- a/src/bindings/python/tests/test_graph/test_constant.py+++ b/src/bindings/python/tests/test_graph/test_constant.py@@ -879,3 +879,50 @@ def test_constant_from_non_contiguous_array_keeps_type(src_dtype, ov_type, make_assert list(ov_const.shape) == list(arr.shape)assert ov_const.data.dtype == arr.dtypeassert np.array_equal(ov_const.data, arr)+++ ("value", "expected"),+ [+ (np.array(["openvino"], dtype=str), ["openvino"]),+ (np.array(["text", "", "x" * 40], dtype=str), ["text", "", "x" * 40]),+ (np.array([["ab", "c"], ["d", "efg"]], dtype=str), ["ab", "c", "d", "efg"]),+ (np.array([b"bytes", b"b"], dtype=np.bytes_), ["bytes", "b"]),+ (np.array("scalar", dtype=str), ["scalar"]),+ (np.array(["openvino", "test"], dtype=str)[::-1], ["test", "openvino"]),+ ],+)+def test_string_constant(value, expected):+ ov_const = ops.constant(value)++ assert isinstance(ov_const, Constant)+ assert ov_const.get_element_type() == Type.string+ assert list(ov_const.shape) == list(value.shape)+ assert ov_const.get_value_strings() == expected+++def test_string_constant_inference():+ value = np.array(["openvino", "string", "constant"], dtype=str)+ param = ops.parameter([3], dtype=Type.string, name="input")+ model = Model([ops.concat([param, ops.constant(value)], axis=0)], [param])++ result = compile_model(model, "CPU")([np.array(["a", "b", "c"], dtype=str)])[0]++ assert list(result) == ["a", "b", "c", "openvino", "string", "constant"]+++def test_string_constant_with_shared_memory():+ with pytest.raises(RuntimeError, match="String types can be only copied"):+ Constant(np.array(["openvino"], dtype=str), shared_memory=True)+++ "value",+ [+ np.array(["\ud800"], dtype=str), # lone surrogate, not encodable to UTF-8+ np.array(["text", "\udfff", "openvino"], dtype=str),+ ],+)+def test_string_constant_not_encodable(value):+ with pytest.raises(UnicodeEncodeError, match="surrogates not allowed"):+ ops.constant(value)diff --git a/src/bindings/python/tests/test_runtime/test_tensor_string.py b/src/bindings/python/tests/test_runtime/test_tensor_string.pyindex f5ef614468b..d1e36176c72 100644--- a/src/bindings/python/tests/test_runtime/test_tensor_string.py+++ b/src/bindings/python/tests/test_runtime/test_tensor_string.py@@ -184,6 +184,29 @@ def test_init_with_numpy(string_data):check_string_based(tensor, string_data)+ ("string_data"),+ [+ (np.array(["text", "abc", "openvino"]).astype("S")[::-1]), # "|S", reversed+ (np.array(["text", "abc", "openvino", "xyz"]).astype(np.bytes_)[::2]), # "|S", strided+ (np.array(["text", "abc", "openvino"])[::-1]), # "<U", reversed+ (np.array([["text", "больше текста"], ["jeszcze więcej słów", "효과가 있었어"]]).T), # "<U", transposed+ ],+)+def test_init_with_non_contiguous_numpy(string_data):+ assert not string_data.flags["C_CONTIGUOUS"]++ tensor = ov.Tensor(string_data, shared_memory=False)++ assert tensor.element_type == ov.Type.string+ # Tensor keeps a C-contiguous copy of the data.+ expected_data = np.ascontiguousarray(string_data)+ # Encoded:+ check_bytes_based(tensor, expected_data)+ # Decoded:+ check_string_based(tensor, expected_data)++@pytest.mark.parametrize(("init_type"),[@@ -340,3 +363,15 @@ def test_invalid_bytes_replaced():check_bytes_based(tensor, string_data, to_flat=True)# Decoded:check_string_based(tensor, np.char.decode(string_data, encoding="utf=8", errors="replace"), to_flat=True)+++ ("string_data"),+ [+ (np.array(["\ud800"])), # lone surrogate, not encodable to UTF-8+ (np.array(["text", "\udfff", "openvino"])),+ ],+)+def test_init_with_numpy_not_encodable_string(string_data):+ with pytest.raises(UnicodeEncodeError, match="surrogates not allowed"):+ ov.Tensor(string_data, shared_memory=False)