From f202e3040e1aee36faa2dfae1135c6a4fae25632 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Thu, 26 Nov 2026 14:59:10 +0100 Subject: [PATCH 1/4] Fix out-of-range Python integers in binary elementwise functions Binary functions raised `OverflowError` or `ValueError` for a Python integer that the array data type cannot hold, where NumPy returns a result, e.g. `dpnp.arctan2(x, 2**63)` or `dpnp.less(x, 2**64)` for an integer array `x`, and `dpnp.logical_and(x, 300)` for an `int8` array `x`. - `dpnp.tensor`: a scalar operand is converted once, to the data type the kernel reads, instead of to the resolved data type and then into a buffer of the kernel's type. This fixes the functions that compute in floating point (`arctan2`, `hypot`, `copysign`, `heaviside`, `logaddexp`, `logaddexp2`, `nextafter`, `float_power`, `ldexp` with a Python integer mantissa, and `divide` of a boolean array), and saves a 0-d allocation and a copy kernel per call. - `DPNPBinaryFunc` takes a `py_int_converter` that replaces a Python integer argument before its data type is resolved: the comparison functions compare an integer array with an integer outside the range of every integer data type as with the infinity of its sign, `dpnp.divide` converts such an integer to a float, and `dpnp.logical_and`, `dpnp.logical_or` and `dpnp.logical_xor` take the truth value of an integer in the `int64` range and raise `OverflowError` outside it, as NumPy does. --- CHANGELOG.md | 1 + dpnp/dpnp_algo/dpnp_elementwise_common.py | 64 +++++++++++++++++++++ dpnp/dpnp_iface_logic.py | 16 +++++- dpnp/dpnp_iface_mathematical.py | 2 + dpnp/tensor/_elementwise_common.py | 21 +++++-- dpnp/tests/tensor/elementwise/test_add.py | 11 ++++ dpnp/tests/tensor/elementwise/test_atan2.py | 16 ++++++ dpnp/tests/test_binary_ufuncs.py | 30 ++++++++++ dpnp/tests/test_logic.py | 45 +++++++++++++++ 9 files changed, 201 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24442cb0da7a..cf2f5cbd5568 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,6 +59,7 @@ 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 [#XXXX](https://github.com/IntelPython/dpnp/pull/XXXX) ### Security diff --git a/dpnp/dpnp_algo/dpnp_elementwise_common.py b/dpnp/dpnp_algo/dpnp_elementwise_common.py index 14ecf295e3f5..6057dc341701 100644 --- a/dpnp/dpnp_algo/dpnp_elementwise_common.py +++ b/dpnp/dpnp_algo/dpnp_elementwise_common.py @@ -73,6 +73,9 @@ "acceptance_fn_negative", "acceptance_fn_sign", "acceptance_fn_subtract", + "py_int_for_comparison", + "py_int_for_divide", + "py_int_for_logical", "resolve_weak_types_2nd_arg_int", ] @@ -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`. """ @@ -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): """ @@ -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, @@ -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) @@ -1428,3 +1446,49 @@ 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 py_int_for_comparison(x, other): + """ + Replace a Python integer outside the range of every integer data type + with the infinity of its sign, which an integer array compares with alike. + + """ + + if other.dtype.kind in "iu" and not _INT64_MIN <= x <= _UINT64_MAX: + return numpy.inf if x > 0 else -numpy.inf + return x + + +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 other.dtype.kind in "iu" and not _INT64_MIN <= x <= _UINT64_MAX: + 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) diff --git a/dpnp/dpnp_iface_logic.py b/dpnp/dpnp_iface_logic.py index 0e626f52204d..a1737b72ccec 100644 --- a/dpnp/dpnp_iface_logic.py +++ b/dpnp/dpnp_iface_logic.py @@ -53,7 +53,12 @@ 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 ( + DPNPBinaryFunc, + DPNPUnaryFunc, + py_int_for_comparison, + py_int_for_logical, +) from .dpnp_array import dpnp_array from .dpnp_utils import get_usm_allocations from .exceptions import ExecutionPlacementError @@ -664,6 +669,7 @@ def array_equiv(a1, a2): ti._equal, _EQUAL_DOCSTRING, weak_type_resolver=_resolve_weak_types_all_py_ints, + py_int_converter=py_int_for_comparison, ) @@ -741,6 +747,7 @@ def array_equiv(a1, a2): ti._greater, _GREATER_DOCSTRING, weak_type_resolver=_resolve_weak_types_all_py_ints, + py_int_converter=py_int_for_comparison, ) @@ -819,6 +826,7 @@ def array_equiv(a1, a2): ti._greater_equal, _GREATER_EQUAL_DOCSTRING, weak_type_resolver=_resolve_weak_types_all_py_ints, + py_int_converter=py_int_for_comparison, ) @@ -1765,6 +1773,7 @@ def isscalar(element): ti._less, _LESS_DOCSTRING, weak_type_resolver=_resolve_weak_types_all_py_ints, + py_int_converter=py_int_for_comparison, ) @@ -1842,6 +1851,7 @@ def isscalar(element): ti._less_equal, _LESS_EQUAL_DOCSTRING, weak_type_resolver=_resolve_weak_types_all_py_ints, + py_int_converter=py_int_for_comparison, ) @@ -1920,6 +1930,7 @@ def isscalar(element): ti._logical_and_result_type, ti._logical_and, _LOGICAL_AND_DOCSTRING, + py_int_converter=py_int_for_logical, ) @@ -2063,6 +2074,7 @@ def isscalar(element): ti._logical_or_result_type, ti._logical_or, _LOGICAL_OR_DOCSTRING, + py_int_converter=py_int_for_logical, ) @@ -2139,6 +2151,7 @@ def isscalar(element): ti._logical_xor_result_type, ti._logical_xor, _LOGICAL_XOR_DOCSTRING, + py_int_converter=py_int_for_logical, ) @@ -2215,4 +2228,5 @@ def isscalar(element): ti._not_equal, _NOT_EQUAL_DOCSTRING, weak_type_resolver=_resolve_weak_types_all_py_ints, + py_int_converter=py_int_for_comparison, ) diff --git a/dpnp/dpnp_iface_mathematical.py b/dpnp/dpnp_iface_mathematical.py index bb7e043c7ab9..1ff6d12c0367 100644 --- a/dpnp/dpnp_iface_mathematical.py +++ b/dpnp/dpnp_iface_mathematical.py @@ -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 @@ -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, ) diff --git a/dpnp/tensor/_elementwise_common.py b/dpnp/tensor/_elementwise_common.py index 844f120269de..093426903e86 100644 --- a/dpnp/tensor/_elementwise_common.py +++ b/dpnp/tensor/_elementwise_common.py @@ -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. @@ -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) @@ -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 = ( diff --git a/dpnp/tests/tensor/elementwise/test_add.py b/dpnp/tests/tensor/elementwise/test_add.py index ce94d863384d..9b270cda98c6 100644 --- a/dpnp/tests/tensor/elementwise/test_add.py +++ b/dpnp/tests/tensor/elementwise/test_add.py @@ -530,3 +530,14 @@ def test_add_out_need_temporary(): dpt.add(x[:6], 1, out=x[-6:]) assert dpt.all(x[:-6] == 1) and dpt.all(x[-6:] == 2) + + +def test_add_out_overlap_scalar_cast(): + q = get_queue_or_skip() + skip_if_dtype_not_supported("f8", q) + + # the kernel reads the float32 scalar as float64 + x = dpt.ones(5, dtype="f8", sycl_queue=q) + r = dpt.add(x, np.float32(2.5), out=x) + assert r is x + assert dpt.all(x == 3.5) diff --git a/dpnp/tests/tensor/elementwise/test_atan2.py b/dpnp/tests/tensor/elementwise/test_atan2.py index 6b77bbcbc72f..aa235e2abd51 100644 --- a/dpnp/tests/tensor/elementwise/test_atan2.py +++ b/dpnp/tests/tensor/elementwise/test_atan2.py @@ -500,3 +500,19 @@ def test_atan2_special_case_ninf_and_ninf(dt): diff = dpt.abs(dpt.subtract(actual, expected)) atol = 8 * dpt.finfo(diff.dtype).eps assert dpt.all(dpt.less_equal(diff, atol)) + + +@pytest.mark.parametrize("dt", ["b1", "i4", "i8", "u8"]) +@pytest.mark.parametrize("val", [2**63, 2**64, -(2**63) - 1]) +def test_atan2_python_int_out_of_dtype_range(dt, val): + q = get_queue_or_skip() + + a = np.array([1, 2, 5], dtype=dt) + x = dpt.asarray(a, sycl_queue=q) + for r, expected in [ + (dpt.atan2(x, val), np.arctan2(a, val)), + (dpt.atan2(val, x), np.arctan2(val, a)), + ]: + assert _compare_dtypes(r.dtype, expected.dtype, sycl_queue=q) + tol = 8 * dpt.finfo(r.dtype).resolution + assert_allclose(dpt.asnumpy(r), expected, atol=tol, rtol=tol) diff --git a/dpnp/tests/test_binary_ufuncs.py b/dpnp/tests/test_binary_ufuncs.py index 2e97047951a8..226700df8f2f 100644 --- a/dpnp/tests/test_binary_ufuncs.py +++ b/dpnp/tests/test_binary_ufuncs.py @@ -816,6 +816,36 @@ def test_f16_corner_values_with_scalar(self, val, scalar): assert_equal(result, expected) +class TestOutOfRangePyInt: + @pytest.mark.parametrize( + "func", + [ + "arctan2", + "copysign", + "divide", + "heaviside", + "hypot", + "logaddexp", + "logaddexp2", + "nextafter", + ], + ) + @pytest.mark.parametrize("val", [2**63, 2**64, -(2**63) - 1]) + @pytest.mark.parametrize("dt", [dpnp.bool] + get_integer_dtypes()) + @numpy.errstate(over="ignore") + def test_float_result(self, func, val, dt): + a = numpy.array([1, 2, 5], dtype=dt) + ia = dpnp.array(a) + + result = getattr(dpnp, func)(ia, val) + expected = getattr(numpy, func)(a, val) + assert_dtype_allclose(result, expected) + + result = getattr(dpnp, func)(val, ia) + expected = getattr(numpy, func)(val, a) + assert_dtype_allclose(result, expected) + + class TestPower: ALL_DTYPES = get_all_dtypes(no_none=True) diff --git a/dpnp/tests/test_logic.py b/dpnp/tests/test_logic.py index 96e28ad96afe..e04cfe278f32 100644 --- a/dpnp/tests/test_logic.py +++ b/dpnp/tests/test_logic.py @@ -19,6 +19,7 @@ get_complex_dtypes, get_float_complex_dtypes, get_float_dtypes, + get_integer_dtypes, get_integer_float_dtypes, numpy_version, ) @@ -425,6 +426,50 @@ def test_comparison_no_broadcast_with_shapes(op, sh1, sh2): getattr(numpy, op)(x1_np, x2_np) +class TestPyIntScalar: + LOGICAL_OPS = ["logical_and", "logical_or", "logical_xor"] + + @pytest.mark.parametrize( + "op", + [ + "equal", + "greater", + "greater_equal", + "less", + "less_equal", + "not_equal", + ], + ) + @pytest.mark.parametrize("val", [-(2**100), -(2**63) - 1, 2**64, 2**100]) + @pytest.mark.parametrize("dt", get_integer_dtypes(all_int_types=True)) + def test_comparison_out_of_range(self, op, val, dt): + info = numpy.iinfo(dt) + a = numpy.array([info.min, 0, info.max], dtype=dt) + ia = dpnp.array(a) + + assert_equal(getattr(dpnp, op)(ia, val), getattr(numpy, op)(a, val)) + assert_equal(getattr(dpnp, op)(val, ia), getattr(numpy, op)(val, a)) + + @pytest.mark.parametrize("op", LOGICAL_OPS) + @pytest.mark.parametrize("val", [0, 2**40, -(2**63), 2**63 - 1]) + @pytest.mark.parametrize("dt", get_all_dtypes(no_none=True)) + def test_logical(self, op, val, dt): + a = numpy.array([0, 1, 0, 3], dtype=dt) + ia = dpnp.array(a) + + assert_equal(getattr(dpnp, op)(ia, val), getattr(numpy, op)(a, val)) + assert_equal(getattr(dpnp, op)(val, ia), getattr(numpy, op)(val, a)) + + @pytest.mark.parametrize("xp", [dpnp, numpy]) + @pytest.mark.parametrize("op", LOGICAL_OPS) + @pytest.mark.parametrize("val", [2**63, -(2**63) - 1]) + @pytest.mark.parametrize("dt", get_all_dtypes(no_none=True)) + def test_logical_out_of_int64_range(self, xp, op, val, dt): + a = xp.array([0, 1], dtype=dt) + assert_raises(OverflowError, getattr(xp, op), a, val) + assert_raises(OverflowError, getattr(xp, op), val, a) + + @pytest.mark.parametrize( "op", ["isfinite", "isinf", "isnan"], ids=["isfinite", "isinf", "isnan"] ) From 0b36ed18fdf615292918fb1ebd46b7c1dde2b5c7 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Thu, 26 Nov 2026 15:07:45 +0100 Subject: [PATCH 2/4] Raise OverflowError for a Python integer no integer dtype can hold in dpnp.tensor `_resolve_weak_types_all_py_ints` resolved a Python integer outside the range of the array data type to `numpy.min_scalar_type` of it, which is the `object` data type for an integer outside the `int64` and `uint64` ranges. The `dpnp.tensor` comparison functions, `dpnp.tensor.divide` and `dpnp.tensor.searchsorted` then raised a misleading `ValueError` ("Unrecognized typenum 17 encountered.", "Dpctl doesn't support dtype object."). They now raise `OverflowError` naming the integer. --- CHANGELOG.md | 1 + dpnp/tensor/_type_utils.py | 17 ++++++++++++-- dpnp/tests/tensor/elementwise/test_less.py | 11 +++++++++ .../tensor/elementwise/test_type_utils.py | 23 +++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf2f5cbd5568..bfa3a7440979 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,7 @@ This release drops support for Python 3.10, making Python 3.11 the minimum requi * 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 [#XXXX](https://github.com/IntelPython/dpnp/pull/XXXX) +* 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` [#XXXX](https://github.com/IntelPython/dpnp/pull/XXXX) ### Security diff --git a/dpnp/tensor/_type_utils.py b/dpnp/tensor/_type_utils.py index cbba43aa09c5..37505545fa6c 100644 --- a/dpnp/tensor/_type_utils.py +++ b/dpnp/tensor/_type_utils.py @@ -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 @@ -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) @@ -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 diff --git a/dpnp/tests/tensor/elementwise/test_less.py b/dpnp/tests/tensor/elementwise/test_less.py index 2d212f66d1e4..cd1a6fb88f11 100644 --- a/dpnp/tests/tensor/elementwise/test_less.py +++ b/dpnp/tests/tensor/elementwise/test_less.py @@ -181,3 +181,14 @@ def test_less_very_large_py_int(): x = dpt.asarray(py_int, dtype="u8") assert not x < -1 assert dpt.less(-1, x) + + +@pytest.mark.parametrize("py_int", [-(2**63) - 1, 2**64]) +def test_less_py_int_out_of_int_range(py_int): + get_queue_or_skip() + + x = dpt.asarray(3, dtype="i8") + with pytest.raises(OverflowError): + dpt.less(x, py_int) + with pytest.raises(OverflowError): + dpt.less(py_int, x) diff --git a/dpnp/tests/tensor/elementwise/test_type_utils.py b/dpnp/tests/tensor/elementwise/test_type_utils.py index 42e096f4f42d..f0ee6fb9c51b 100644 --- a/dpnp/tests/tensor/elementwise/test_type_utils.py +++ b/dpnp/tests/tensor/elementwise/test_type_utils.py @@ -252,3 +252,26 @@ def test_arg_validation(): wt = tu.WeakFloatingType(2.0) with pytest.raises(ValueError): tu._resolve_weak_types(wt, wt, None) + + +def test_resolve_weak_types_all_py_ints_min_int_dtype(): + dev = MockDevice(fp16=True, fp64=True) + + wit = tu.WeakIntegralType(2**63) + res = tu._resolve_weak_types_all_py_ints(wit, dpt.int64, dev) + assert res == (dpt.uint64, dpt.int64) + + wit = tu.WeakIntegralType(-1) + res = tu._resolve_weak_types_all_py_ints(dpt.uint8, wit, dev) + assert res == (dpt.uint8, dpt.int8) + + +@pytest.mark.parametrize("val", [-(2**63) - 1, 2**64]) +def test_resolve_weak_types_all_py_ints_out_of_int_range(val): + dev = MockDevice(fp16=True, fp64=True) + wit = tu.WeakIntegralType(val) + + with pytest.raises(OverflowError): + tu._resolve_weak_types_all_py_ints(wit, dpt.int8, dev) + with pytest.raises(OverflowError): + tu._resolve_weak_types_all_py_ints(dpt.int8, wit, dev) From 98d6968e1db51786507d45fead913272455eda26 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Thu, 26 Nov 2026 17:10:34 +0100 Subject: [PATCH 3/4] Compare an integer array with an out-of-range Python integer without casting it The comparison functions replaced a Python integer outside the range of every integer data type with an infinity, which cast the integer array to a floating-point data type. NumPy's result depends on the sign of the integer alone, so `DPNPBinaryComparisonFunc` computes it from the sign and returns the array compared with the maximum of its data type, which is true or false for every element and keeps the checks of `out` and the layout of any comparison. With `dtype` given, the integer goes through the usual path. `py_int_for_divide` checks the range of the integer before the data type of the other argument, which most calls then skip. --- dpnp/dpnp_algo/dpnp_elementwise_common.py | 58 ++++++++++++++--- dpnp/dpnp_iface_logic.py | 27 +++----- dpnp/tests/test_logic.py | 77 +++++++++++++++++++---- 3 files changed, 121 insertions(+), 41 deletions(-) diff --git a/dpnp/dpnp_algo/dpnp_elementwise_common.py b/dpnp/dpnp_algo/dpnp_elementwise_common.py index 6057dc341701..33ae5e0b34f4 100644 --- a/dpnp/dpnp_algo/dpnp_elementwise_common.py +++ b/dpnp/dpnp_algo/dpnp_elementwise_common.py @@ -59,6 +59,7 @@ __all__ = [ "DPNPI0", "DPNPAngle", + "DPNPBinaryComparisonFunc", "DPNPBinaryFunc", "DPNPBinaryFuncOutKw", "DPNPBinaryTwoOutputsFunc", @@ -73,7 +74,6 @@ "acceptance_fn_negative", "acceptance_fn_sign", "acceptance_fn_subtract", - "py_int_for_comparison", "py_int_for_divide", "py_int_for_logical", "resolve_weak_types_2nd_arg_int", @@ -879,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) + + class DPNPBinaryTwoOutputsFunc(BinaryElementwiseFunc): """ Class that implements binary element-wise functions with two output arrays. @@ -1458,16 +1498,14 @@ def _is_py_int(x): return isinstance(x, int) and not isinstance(x, bool) -def py_int_for_comparison(x, other): - """ - Replace a Python integer outside the range of every integer data type - with the infinity of its sign, which an integer array compares with alike. +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" - """ - if other.dtype.kind in "iu" and not _INT64_MIN <= x <= _UINT64_MAX: - return numpy.inf if x > 0 else -numpy.inf - return x +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): @@ -1477,7 +1515,7 @@ def py_int_for_divide(x, other): """ - if other.dtype.kind in "iu" and not _INT64_MIN <= x <= _UINT64_MAX: + if not _INT64_MIN <= x <= _UINT64_MAX and other.dtype.kind in "iu": return float(x) return x diff --git a/dpnp/dpnp_iface_logic.py b/dpnp/dpnp_iface_logic.py index a1737b72ccec..e7fbec0e626f 100644 --- a/dpnp/dpnp_iface_logic.py +++ b/dpnp/dpnp_iface_logic.py @@ -51,12 +51,11 @@ 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 ( + DPNPBinaryComparisonFunc, DPNPBinaryFunc, DPNPUnaryFunc, - py_int_for_comparison, py_int_for_logical, ) from .dpnp_array import dpnp_array @@ -663,13 +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, - py_int_converter=py_int_for_comparison, ) @@ -741,13 +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, - py_int_converter=py_int_for_comparison, ) @@ -820,13 +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, - py_int_converter=py_int_for_comparison, ) @@ -1767,13 +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, - py_int_converter=py_int_for_comparison, ) @@ -1845,13 +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, - py_int_converter=py_int_for_comparison, ) @@ -2222,11 +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, - py_int_converter=py_int_for_comparison, ) diff --git a/dpnp/tests/test_logic.py b/dpnp/tests/test_logic.py index e04cfe278f32..8b173039cce7 100644 --- a/dpnp/tests/test_logic.py +++ b/dpnp/tests/test_logic.py @@ -427,19 +427,17 @@ def test_comparison_no_broadcast_with_shapes(op, sh1, sh2): class TestPyIntScalar: + COMPARISON_OPS = [ + "equal", + "greater", + "greater_equal", + "less", + "less_equal", + "not_equal", + ] LOGICAL_OPS = ["logical_and", "logical_or", "logical_xor"] - @pytest.mark.parametrize( - "op", - [ - "equal", - "greater", - "greater_equal", - "less", - "less_equal", - "not_equal", - ], - ) + @pytest.mark.parametrize("op", COMPARISON_OPS) @pytest.mark.parametrize("val", [-(2**100), -(2**63) - 1, 2**64, 2**100]) @pytest.mark.parametrize("dt", get_integer_dtypes(all_int_types=True)) def test_comparison_out_of_range(self, op, val, dt): @@ -450,6 +448,63 @@ def test_comparison_out_of_range(self, op, val, dt): assert_equal(getattr(dpnp, op)(ia, val), getattr(numpy, op)(a, val)) assert_equal(getattr(dpnp, op)(val, ia), getattr(numpy, op)(val, a)) + @pytest.mark.parametrize("op", COMPARISON_OPS) + @pytest.mark.parametrize("val", [-(2**63) - 1, 2**64]) + def test_comparison_out_of_range_out_order(self, op, val): + a = numpy.asfortranarray( + numpy.arange(6, dtype=numpy.int16).reshape(2, 3) + ) + ia = dpnp.array(a, order="F") + + for x1, x2, ix1, ix2 in [(a, val, ia, val), (val, a, val, ia)]: + expected = getattr(numpy, op)(x1, x2) + result = getattr(dpnp, op)(ix1, ix2) + assert_equal(result, expected) + assert result.flags.f_contiguous + + iout = dpnp.empty(expected.shape, dtype=dpnp.bool) + result = getattr(dpnp, op)(ix1, ix2, out=iout) + assert result is iout + assert_equal(result, expected) + + @pytest.mark.parametrize( + "op", + [ + operator.eq, + operator.ge, + operator.gt, + operator.le, + operator.lt, + operator.ne, + ], + ) + def test_comparison_out_of_range_operator(self, op): + a = numpy.array([-1, 0, 1]) + ia = dpnp.array(a) + assert_equal(op(ia, 2**64), op(a, 2**64)) + assert_equal(op(-(2**64), ia), op(-(2**64), a)) + + @pytest.mark.parametrize("op", COMPARISON_OPS) + def test_comparison_out_of_range_dtype(self, op): + # with `dtype`, the integer is converted to it as any scalar operand + ia = dpnp.array([1, 2, 3]) + assert_raises(OverflowError, getattr(dpnp, op), ia, 2**64, dtype="i8") + + @pytest.mark.parametrize("xp", [dpnp, numpy]) + @pytest.mark.parametrize("op", COMPARISON_OPS) + def test_comparison_out_of_range_bool(self, xp, op): + a = xp.array([True, False]) + assert_raises(OverflowError, getattr(xp, op), a, 2**64) + assert_raises(OverflowError, getattr(xp, op), 2**64, a) + + @pytest.mark.parametrize("op", COMPARISON_OPS) + @pytest.mark.parametrize("dt", get_float_dtypes()) + def test_comparison_out_of_range_float(self, op, dt): + a = numpy.array([1.0, 2**64, numpy.inf], dtype=dt) + ia = dpnp.array(a) + assert_equal(getattr(dpnp, op)(ia, 2**64), getattr(numpy, op)(a, 2**64)) + assert_equal(getattr(dpnp, op)(2**64, ia), getattr(numpy, op)(2**64, a)) + @pytest.mark.parametrize("op", LOGICAL_OPS) @pytest.mark.parametrize("val", [0, 2**40, -(2**63), 2**63 - 1]) @pytest.mark.parametrize("dt", get_all_dtypes(no_none=True)) From 0a6eb7cb8e99caf495e9a5efa8159161368e673b Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Thu, 26 Nov 2026 17:11:15 +0100 Subject: [PATCH 4/4] Link the changelog entries to the PR --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa3a7440979..4ec667010f04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,8 +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 [#XXXX](https://github.com/IntelPython/dpnp/pull/XXXX) -* 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` [#XXXX](https://github.com/IntelPython/dpnp/pull/XXXX) +* 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) ### Security