diff --git a/onnxscript/optimizer/_constant_folding.py b/onnxscript/optimizer/_constant_folding.py index e0b0f59c31..6f11ae7ec9 100644 --- a/onnxscript/optimizer/_constant_folding.py +++ b/onnxscript/optimizer/_constant_folding.py @@ -278,9 +278,18 @@ def _get_numpy_value( if size_limit is not None and const_value.size > size_limit: return None try: - # Reinterpret the array with `.view()` because some implementations of - # ir.TensorProtocol (e.g. PyTorch<=2.7) do not use ml_dtypes for bfloat16 etc. - array = const_value.numpy().view(const_value.dtype.numpy()) + # Turn the constant value into a numpy array representation with the + # specifics of this conversion handled by the tensor type + array = const_value.numpy() + # Can/should not reinterpret strings via .view, resulting in + # "TypeError: Cannot change data-type for array of references." + # There is also no reason to reinterpret strings, this is only + # relevant for some arithmetic types + if const_value.dtype != ir.DataType.STRING: + # Reinterpret the array with `.view()` because some + # implementations of ir.TensorProtocol (e.g. PyTorch<=2.7) do + # not use ml_dtypes for bfloat16 etc. + array = array.view(const_value.dtype.numpy()) except FileNotFoundError: # External data is not available. logger.warning(