Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi
* Fixed `dpnp.partition` to accept NumPy integers and integer arrays as `kth`, and to raise as NumPy does for a boolean or an empty `kth` [#3138](https://github.com/IntelPython/dpnp/pull/3138)
* Fixed `dpnp.nanmedian` raising `TypeError` for an `out` array of a lower precision data type instead of casting to it as `dpnp.median` does [#3138](https://github.com/IntelPython/dpnp/pull/3138)
* Fixed a `TypeError` in `dpnp.from_dlpack` and `dpnp.tensor.from_dlpack` when importing a DLPack tensor on a oneAPI device with a NULL data pointer, which DLPack asks for in a tensor of size zero [#3197](https://github.com/IntelPython/dpnp/pull/3197)
* Fixed binary functions raising `OverflowError` or `ValueError` for a Python integer outside the range of the array data type. The logical functions now raise `OverflowError` for a Python integer outside the `int64` range for any data type [#3202](https://github.com/IntelPython/dpnp/pull/3202)
* Fixed the misleading `ValueError` about an unsupported data type that `dpnp.tensor` comparison functions, `dpnp.tensor.divide` and `dpnp.tensor.searchsorted` raised for a Python integer outside the `int64` and `uint64` ranges, which now raise `OverflowError` [#3202](https://github.com/IntelPython/dpnp/pull/3202)
Comment on lines +62 to +63

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: The first entry reads as if every binary function now accepts such an integer, but dpnp.add(int8_array, 300) still raises OverflowError, as in NumPy. Could it name the fixed groups (comparisons, dpnp.divide, the logical functions and those computing in floating point)? dpnp.tensor.isin also changes from ValueError to OverflowError and could go in the second entry.


### Security

Expand Down
102 changes: 102 additions & 0 deletions dpnp/dpnp_algo/dpnp_elementwise_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
__all__ = [
"DPNPI0",
"DPNPAngle",
"DPNPBinaryComparisonFunc",
"DPNPBinaryFunc",
"DPNPBinaryFuncOutKw",
"DPNPBinaryTwoOutputsFunc",
Expand All @@ -73,6 +74,8 @@
"acceptance_fn_negative",
"acceptance_fn_sign",
"acceptance_fn_subtract",
"py_int_for_divide",
"py_int_for_logical",
"resolve_weak_types_2nd_arg_int",
]

Expand Down Expand Up @@ -598,6 +601,13 @@ class DPNPBinaryFunc(BinaryElementwiseFunc):
sycl_dev - The :class:`dpctl.SyclDevice` where the function
evaluation is carried out.
One of `o1_dtype` and `o2_dtype` must be a ``dtype`` instance.
py_int_converter : {None, callable}, optional
Function that replaces a Python integer argument of this binary
function before its data type is resolved. The function takes
2 arguments:
x - The Python integer argument
other - The other argument, an array
and returns the scalar to use instead of `x`.

"""

Expand All @@ -612,6 +622,7 @@ def __init__(
binary_inplace_fn=None,
acceptance_fn=None,
weak_type_resolver=None,
py_int_converter=None,
):
def _call_func(src1, src2, dst, sycl_queue, depends=None):
"""
Expand Down Expand Up @@ -642,6 +653,7 @@ def _call_func(src1, src2, dst, sycl_queue, depends=None):
weak_type_resolver=weak_type_resolver,
)
self.__name__ = "DPNPBinaryFunc"
self.py_int_converter_ = py_int_converter

def __call__(
self,
Expand Down Expand Up @@ -680,6 +692,12 @@ def __call__(
"as an argument, but both were provided."
)

if self.py_int_converter_ is not None:
if _is_py_int(x1):
x1 = self.py_int_converter_(x1, x2)
elif _is_py_int(x2):
x2 = self.py_int_converter_(x2, x1)

x1_usm = dpnp.get_usm_ndarray_or_scalar(x1)
x2_usm = dpnp.get_usm_ndarray_or_scalar(x2)

Expand Down Expand Up @@ -861,6 +879,46 @@ def __call__(self, *args, **kwargs):
return super().__call__(*args, **kwargs)


class DPNPBinaryComparisonFunc(DPNPBinaryFunc):
"""
DPNPBinaryFunc of a comparison function.

NumPy compares an integer array with a Python integer outside the range of
every integer data type by the sign of the integer alone, so all elements
get the same result. Comparing the array with the maximum of its data type
instead gives that result without casting the array.

"""

def __init__(self, name, result_type_resolver_fn, binary_dp_impl_fn, docs):
super().__init__(
name,
result_type_resolver_fn,
binary_dp_impl_fn,
docs,
weak_type_resolver=dtu._resolve_weak_types_all_py_ints,
)

@wraps(DPNPBinaryFunc.__call__)
def __call__(self, x1, x2, /, out=None, **kwargs):
if kwargs.get("dtype") is None:
if _is_out_of_int_range(x1) and _is_int_array(x2):
signs = (1 if x1 > 0 else -1, 0)
return self._same_for_all(x2, signs, out, kwargs)
if _is_out_of_int_range(x2) and _is_int_array(x1):
signs = (0, 1 if x2 > 0 else -1)
return self._same_for_all(x1, signs, out, kwargs)
return super().__call__(x1, x2, out, **kwargs)

def _same_for_all(self, a, signs, out, kwargs):
# the integer's sign compared with 0 stands for any element of `a`
value = getattr(numpy, self.name_)(*signs)
# every element of `a` is `<=` its maximum and none is `>`; unlike
# dpnp.full, a comparison checks `out` and lays out the result as usual
func = dpnp.less_equal if value else dpnp.greater
return func(a, numpy.iinfo(a.dtype).max, out=out, **kwargs)
Comment on lines +903 to +919

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For an integer out of every integer range, this shortcut skips the argument checks of DPNPBinaryFunc.__call__ and passes kwargs on to dpnp.less_equal or dpnp.greater, so the error names a function the user did not call:

import dpnp

a = dpnp.arange(3)
dpnp.less(a, 2**70, casting="no")
# NotImplementedError: Requested function=less_equal with kwargs={'casting': 'no'} isn't currently supported.

Could the checks run before the shortcut, e.g. in a helper both __call__ use?



class DPNPBinaryTwoOutputsFunc(BinaryElementwiseFunc):
"""
Class that implements binary element-wise functions with two output arrays.
Expand Down Expand Up @@ -1428,3 +1486,47 @@ def resolve_weak_types_2nd_arg_int(o1_dtype, o2_dtype, sycl_dev):
dti.default_device_int_type(sycl_dev)
)
return dtu._resolve_weak_types(o1_dtype, o2_dtype, sycl_dev)


_INT64_MIN = numpy.iinfo(numpy.int64).min
_INT64_MAX = numpy.iinfo(numpy.int64).max
_UINT64_MAX = numpy.iinfo(numpy.uint64).max


def _is_py_int(x):
"""Return ``True`` if `x` is a Python integer, but not a boolean."""
return isinstance(x, int) and not isinstance(x, bool)


def _is_int_array(x):
"""Return ``True`` if `x` is a supported array of an integer data type."""
return dpnp.is_supported_array_type(x) and x.dtype.kind in "iu"


def _is_out_of_int_range(x):
"""Return ``True`` if no integer data type can hold the Python integer `x`."""
return _is_py_int(x) and not _INT64_MIN <= x <= _UINT64_MAX


def py_int_for_divide(x, other):
"""
Convert a Python integer outside the range of every integer data type
to a float, as NumPy divides an integer array by it in floating point.

"""

if not _INT64_MIN <= x <= _UINT64_MAX and other.dtype.kind in "iu":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This repeats _is_out_of_int_range and _is_int_array defined above. if _is_out_of_int_range(x) and _is_int_array(other): would keep the range check in one place.

return float(x)
return x


def py_int_for_logical(x, _other):
"""
Convert a Python integer to its truth value, as NumPy converts it to int64
first and so raises outside the int64 range.

"""

if not _INT64_MIN <= x <= _INT64_MAX:
raise OverflowError(f"Python integer {x} out of bounds for int64")
return bool(x)
29 changes: 15 additions & 14 deletions dpnp/dpnp_iface_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,13 @@
import dpnp
import dpnp.libtensor._tensor_elementwise_impl as ti
import dpnp.tensor as dpt
from dpnp.tensor._type_utils import _resolve_weak_types_all_py_ints

from .dpnp_algo.dpnp_elementwise_common import DPNPBinaryFunc, DPNPUnaryFunc
from .dpnp_algo.dpnp_elementwise_common import (
DPNPBinaryComparisonFunc,
DPNPBinaryFunc,
DPNPUnaryFunc,
py_int_for_logical,
)
from .dpnp_array import dpnp_array
from .dpnp_utils import get_usm_allocations
from .exceptions import ExecutionPlacementError
Expand Down Expand Up @@ -658,12 +662,11 @@ def array_equiv(a1, a2):

"""

equal = DPNPBinaryFunc(
equal = DPNPBinaryComparisonFunc(
"equal",
ti._equal_result_type,
ti._equal,
_EQUAL_DOCSTRING,
weak_type_resolver=_resolve_weak_types_all_py_ints,
)


Expand Down Expand Up @@ -735,12 +738,11 @@ def array_equiv(a1, a2):

"""

greater = DPNPBinaryFunc(
greater = DPNPBinaryComparisonFunc(
"greater",
ti._greater_result_type,
ti._greater,
_GREATER_DOCSTRING,
weak_type_resolver=_resolve_weak_types_all_py_ints,
)


Expand Down Expand Up @@ -813,12 +815,11 @@ def array_equiv(a1, a2):

"""

greater_equal = DPNPBinaryFunc(
greater_equal = DPNPBinaryComparisonFunc(
"greater_equal",
ti._greater_equal_result_type,
ti._greater_equal,
_GREATER_EQUAL_DOCSTRING,
weak_type_resolver=_resolve_weak_types_all_py_ints,
)


Expand Down Expand Up @@ -1759,12 +1760,11 @@ def isscalar(element):

"""

less = DPNPBinaryFunc(
less = DPNPBinaryComparisonFunc(
"less",
ti._less_result_type,
ti._less,
_LESS_DOCSTRING,
weak_type_resolver=_resolve_weak_types_all_py_ints,
)


Expand Down Expand Up @@ -1836,12 +1836,11 @@ def isscalar(element):

"""

less_equal = DPNPBinaryFunc(
less_equal = DPNPBinaryComparisonFunc(
"less_equal",
ti._less_equal_result_type,
ti._less_equal,
_LESS_EQUAL_DOCSTRING,
weak_type_resolver=_resolve_weak_types_all_py_ints,
)


Expand Down Expand Up @@ -1920,6 +1919,7 @@ def isscalar(element):
ti._logical_and_result_type,
ti._logical_and,
_LOGICAL_AND_DOCSTRING,
py_int_converter=py_int_for_logical,
)


Expand Down Expand Up @@ -2063,6 +2063,7 @@ def isscalar(element):
ti._logical_or_result_type,
ti._logical_or,
_LOGICAL_OR_DOCSTRING,
py_int_converter=py_int_for_logical,
)


Expand Down Expand Up @@ -2139,6 +2140,7 @@ def isscalar(element):
ti._logical_xor_result_type,
ti._logical_xor,
_LOGICAL_XOR_DOCSTRING,
py_int_converter=py_int_for_logical,
)


Expand Down Expand Up @@ -2209,10 +2211,9 @@ def isscalar(element):

"""

not_equal = DPNPBinaryFunc(
not_equal = DPNPBinaryComparisonFunc(
"not_equal",
ti._not_equal_result_type,
ti._not_equal,
_NOT_EQUAL_DOCSTRING,
weak_type_resolver=_resolve_weak_types_all_py_ints,
)
2 changes: 2 additions & 0 deletions dpnp/dpnp_iface_mathematical.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
acceptance_fn_negative,
acceptance_fn_sign,
acceptance_fn_subtract,
py_int_for_divide,
resolve_weak_types_2nd_arg_int,
)
from .dpnp_array import dpnp_array
Expand Down Expand Up @@ -1542,6 +1543,7 @@ def diff(a, n=1, axis=-1, prepend=None, append=None):
binary_inplace_fn=ti._divide_inplace,
acceptance_fn=dtu._acceptance_fn_divide,
weak_type_resolver=dtu._resolve_weak_types_all_py_ints,
py_int_converter=py_int_for_divide,
)


Expand Down
21 changes: 17 additions & 4 deletions dpnp/tensor/_elementwise_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@
)


def _scalar_to_usm_ndarray(o, o_dtype, buf_dt, exec_q):
"""
Converts a scalar operand to the data type the kernel reads, `buf_dt`, or
to `o_dtype` when the kernel reads that one.
"""
# one conversion keeps a Python int that `o_dtype` can't hold from overflow
dt = o_dtype if buf_dt is None else buf_dt
return dpt.asarray(o, dtype=dt, sycl_queue=exec_q)


class UnaryElementwiseFunc:
"""
Class that implements unary element-wise functions.
Expand Down Expand Up @@ -600,9 +610,10 @@ def __call__(self, o1, o2, /, *, out=None, order="K"):
):
buf2_dt = o2_dtype
else:
src2 = dpt.asarray(
o2, dtype=o2_dtype, sycl_queue=exec_q
src2 = _scalar_to_usm_ndarray(
o2, o2_dtype, buf2_dt, exec_q
)
buf2_dt = None
if buf2_dt is None:
if src2.shape != res_shape:
src2 = dpt.broadcast_to(src2, res_shape)
Expand Down Expand Up @@ -652,11 +663,13 @@ def __call__(self, o1, o2, /, *, out=None, order="K"):
if isinstance(o1, dpt.usm_ndarray):
src1 = o1
else:
src1 = dpt.asarray(o1, dtype=o1_dtype, sycl_queue=exec_q)
src1 = _scalar_to_usm_ndarray(o1, o1_dtype, buf1_dt, exec_q)
buf1_dt = None
if isinstance(o2, dpt.usm_ndarray):
src2 = o2
else:
src2 = dpt.asarray(o2, dtype=o2_dtype, sycl_queue=exec_q)
src2 = _scalar_to_usm_ndarray(o2, o2_dtype, buf2_dt, exec_q)
buf2_dt = None

if order == "A":
order = (
Expand Down
17 changes: 15 additions & 2 deletions dpnp/tensor/_type_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,19 @@ def _resolve_weak_types(o1_dtype, o2_dtype, dev):
return o1_dtype, o2_dtype


def _min_int_dtype(val):
"""
Returns the smallest integer data type that can hold the Python integer
`val`, or raises `OverflowError` when no integer data type can.
"""
dt = np.min_scalar_type(val)
if dt.kind not in "iu":
raise OverflowError(
f"Python integer {val} out of bounds for every integer data type"
)
return dpt.dtype(dt)


def _resolve_weak_types_all_py_ints(o1_dtype, o2_dtype, dev):
"""
Resolves weak data type per NEP-0050 for comparisons and
Expand Down Expand Up @@ -456,7 +469,7 @@ def _resolve_weak_types_all_py_ints(o1_dtype, o2_dtype, dev):
o1_val = o1_dtype.get()
o2_iinfo = dpt.iinfo(o2_dtype)
if (o1_val < o2_iinfo.min) or (o1_val > o2_iinfo.max):
return dpt.dtype(np.min_scalar_type(o1_val)), o2_dtype
return _min_int_dtype(o1_val), o2_dtype
return o2_dtype, o2_dtype
elif _is_weak_dtype(o2_dtype):
o1_kind_num = _strong_dtype_num_kind(o1_dtype)
Expand All @@ -479,7 +492,7 @@ def _resolve_weak_types_all_py_ints(o1_dtype, o2_dtype, dev):
o2_val = o2_dtype.get()
o1_iinfo = dpt.iinfo(o1_dtype)
if (o2_val < o1_iinfo.min) or (o2_val > o1_iinfo.max):
return o1_dtype, dpt.dtype(np.min_scalar_type(o2_val))
return o1_dtype, _min_int_dtype(o2_val)
return o1_dtype, o1_dtype
else:
return o1_dtype, o2_dtype
Expand Down
Loading
Loading