Skip to content
Merged
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 @@ -66,6 +66,8 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi
* Fixed wrong values from `dpnp.from_dlpack` and `dpnp.tensor.from_dlpack` when copying a `float64` or `complex128` host array to a SYCL device without fp64 support, which copied its bytes unchanged into the `float32` or `complex64` result [#3209](https://github.com/IntelPython/dpnp/pull/3209)
* Fixed a random segfault of the OpenCL CPU runtime in coverage builds, and their link failure with `DPNP_TENSOR_GENERATE_COVERAGE_FOR_PYBIND11_EXTENSIONS=ON`, by instrumenting only host code [#3193](https://github.com/IntelPython/dpnp/pull/3193)
* Fixed building with the open source DPC++ compiler and CMake 4.5 or newer, which identifies it as `DPClang` instead of `Clang` [#3216](https://github.com/IntelPython/dpnp/pull/3216)
* Fixed the comparison functions, `dpnp.divide`, the logical functions and the binary functions that compute in floating point for an integer or boolean array, such as `dpnp.arctan2`, 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`, `dpnp.tensor.isin` 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)

### Security

Expand Down
159 changes: 139 additions & 20 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 All @@ -659,26 +671,13 @@ def __call__(
dpnp.check_supported_arrays_type(
x1, x2, scalar_type=True, all_scalars=False
)
if kwargs:
raise NotImplementedError(
f"Requested function={self.name_} with kwargs={kwargs} "
"isn't currently supported."
)
elif where is not True:
raise NotImplementedError(
f"Requested function={self.name_} with where={where} "
"isn't currently supported."
)
elif subok is not True:
raise NotImplementedError(
f"Requested function={self.name_} with subok={subok} "
"isn't currently supported."
)
elif dtype is not None and out is not None:
raise TypeError(
f"Requested function={self.name_} only takes `out` or `dtype` "
"as an argument, but both were provided."
)
self._check_args(out, where, dtype, subok, kwargs)

if self.py_int_converter_ is not None:
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
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 @@ -737,6 +736,29 @@ def __call__(
return out
return dpnp_array._create_from_usm_ndarray(res_usm)

def _check_args(self, out, where, dtype, subok, kwargs):
"""Raise for arguments of a call that this function does not support."""
if kwargs:
raise NotImplementedError(
f"Requested function={self.name_} with kwargs={kwargs} "
"isn't currently supported."
)
elif where is not True:
raise NotImplementedError(
f"Requested function={self.name_} with where={where} "
"isn't currently supported."
)
elif subok is not True:
raise NotImplementedError(
f"Requested function={self.name_} with subok={subok} "
"isn't currently supported."
)
elif dtype is not None and out is not None:
raise TypeError(
f"Requested function={self.name_} only takes `out` or `dtype` "
"as an argument, but both were provided."
)

def outer(
self,
x1,
Expand Down Expand Up @@ -861,6 +883,59 @@ 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,
*,
where=True,
order="K",
dtype=None,
subok=True,
**kwargs,
):
# check here, so an error names this function, not `func` below
self._check_args(out, where, dtype, subok, 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, order=order)


class DPNPBinaryTwoOutputsFunc(BinaryElementwiseFunc):
"""
Class that implements binary element-wise functions with two output arrays.
Expand Down Expand Up @@ -1428,3 +1503,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 _is_out_of_int_range(x) and _is_int_array(other):
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
Loading
Loading