dpctl icon indicating copy to clipboard operation
dpctl copied to clipboard

out of bound inputs for `uint8` and `uint16` data types

Open vtavana opened this issue 2 years ago • 1 comments

The following cases behave differently in dpctl and NumPy.

import dpctl,dpctl.tensor as dpt, numpy
 # uint8, with floating point input
>>> a=numpy.array(60025, dtype=numpy.float32)
>>> a.astype(numpy.uint8)
array(121, dtype=uint8)
 
>>> a=dpt.asarray(60025, dtype=numpy.float32)
>>> dpt.astype(a, numpy.uint8)
usm_ndarray(127, dtype=uint8)
 
 # uint8, with integer input works fine
>>> a=dpt.asarray(60025, dtype=numpy.int64)
>>> dpt.astype(a, numpy.uint8)
usm_ndarray(121, dtype=uint8)

 # uint16, with floating point input
>>> a=numpy.array(60025, dtype=numpy.float32)
>>> a.astype(numpy.uint16)
array(60025, dtype=uint16)

>>> a=dpt.asarray(a,dtype=numpy.uint16)
>>> dpt.astype(a, numpy.uint16)
usm_ndarray(32767, dtype=uint16)

vtavana avatar Feb 09 '24 16:02 vtavana

This is considered an undefined behavior, and is not guaranteed by NumPy with transition from one CPU architecture to another. Perhaps dpctl could, internally, cast floating point number to the largest integral type first, and then cast the result to a smaller integral type, but compiler considers any casting from floating point type to integral type an undefined behavior (see https://en.cppreference.com/w/cpp/language/implicit_conversion, section Floating-Integral conversion):

If the truncated value cannot fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithmetic does not apply).

oleksandr-pavlyk avatar Feb 13 '24 14:02 oleksandr-pavlyk