Repository navigation
[PyOV] Fix creation of Constant from numpy string arrays - #38942
Iyanuoluwa007 wants to merge 1 commit into
Conversation
Creating a Constant from a numpy array of str_ or bytes_ passed the raw fixed-width numpy buffer to the Constant constructor as if it held std::string objects. Depending on the data this crashed the interpreter or raised MemoryError. Convert string arrays element by element into a string Tensor before creating the Constant, the same way Tensor creation already does. Also make non-contiguous string arrays contiguous instead of throwing, and raise a clear error when shared memory is requested for strings, since string data can only be copied. Closes openvinotoolkit#23611
Somay-kousis
left a comment
There was a problem hiding this comment.
Checked the master behaviour on macOS arm64 with the 2026.5.0 nightly wheel. There it doesn't crash or raise. Every string just comes back empty, so on some platforms this is a silent wrong value:
| call | master |
|---|---|
ops.constant(np.array(["openvino"], dtype=str)).get_value_strings() |
[''] |
ops.constant(np.array(["text", "", "x" * 40], dtype=str)) |
['', '', ''] |
ops.constant(np.array([b"bytes", b"b"], dtype=np.bytes_)) |
['', ''] |
ops.constant(np.array("scalar", dtype=str)) |
[''] |
Constant(Tensor(np.array(["a", "bc"]))) already gives ['a', 'bc'], so routing through the string Tensor helper matches what that path does.
One behaviour change outside Constant: as_contiguous is also used by Tensor's create_copied (common.cpp, the !is_contiguous branch before fill_string_tensor_data). On master, Tensor(np.array(["openvino", "test"], dtype=str)[::-1]) raises RuntimeError: Tensor cannot be created as contiguous!. With the new case ov::element::string it should copy instead. That looks like the right behaviour, but only the Constant side is tested. A case in test_tensor_string.py for a reversed or strided str_ and bytes_ array would cover the Tensor change too. I didn't build the branch, so the after-state for Tensor is inferred from the diff.
Details:
Constantfrom a numpystr_/bytes_array passed the fixed-width numpy buffer to the stringConstantconstructor as if it heldstd::stringobjects. Depending on the data this crashed the interpreter or raisedMemoryError: bad allocation.Tensorfirst, using the same helper theTensorconstructor already uses, and build theConstantfrom it.as_contiguousinstead of throwing, and raise a clear error when shared memory is requested for strings (string data can only be copied), matchingTensor.Tickets:
AI Assistance:
test_constant.pyotherwise unchanged apart from tests that need the AUTO plugin, which was not part of the local build;test_tensor.pyandtest_tensor_string.py: 636 passed; clang-format 18 and flake8 clean.