Skip to content

Fix out-of-range Python integers in binary elementwise functions - #3202

Open
antonwolfy wants to merge 4 commits into
masterfrom
fix-out-of-range-py-int-in-binary-ufuncs
Open

antonwolfy wants to merge 4 commits into
masterfrom
fix-out-of-range-py-int-in-binary-ufuncs

Conversation

@antonwolfy

Copy link
Copy Markdown
Contributor

Binary elementwise functions raised OverflowError or ValueError for a Python integer that the array data type cannot hold, where NumPy returns a result:

import dpnp as np

x = np.array([1, 2], dtype=np.int32)
np.arctan2(x, 2**63)  # OverflowError: Python int too large to convert to C long
np.less(x, 2**64)  # ValueError: Unrecognized typenum 17 encountered.
np.logical_and(np.array([0, 1], dtype=np.int8), 300)  # OverflowError: Python integer 300 out of bounds for int8

This PR:

  • In dpnp.tensor, converts a scalar operand once, to the data type the kernel reads, instead of to the resolved data type and then into a 0-d buffer of the kernel's data type. This fixes the functions that compute in floating point for an integer or boolean array (arctan2, hypot, copysign, heaviside, logaddexp, logaddexp2, nextafter, float_power, ldexp with a Python integer mantissa, and divide of a boolean array), and saves an allocation and a copy kernel per call.
  • Gives the comparison functions NumPy's result for an integer array and a Python integer outside the range of every integer data type, which depends on the sign of the integer alone. The array is compared with the maximum of its data type instead, so it is not cast.
  • Converts such an integer to a float in dpnp.divide.
  • Takes the truth value of a Python integer in dpnp.logical_and, dpnp.logical_or and dpnp.logical_xor after checking that it fits int64, as NumPy does. Outside that range they now raise OverflowError for every array data type, as NumPy does, where they used to return a result for a floating-point array.
  • Raises OverflowError instead of a misleading ValueError in the dpnp.tensor comparison functions, dpnp.tensor.divide and dpnp.tensor.searchsorted for a Python integer outside the int64 and uint64 ranges.

The Array API standard leaves all these cases unspecified: a Python integer outside the bounds of the array data type, integer arrays in atan2 and similar functions, and Python integers in the logical functions. Results of the cases the standard covers do not change.

Not changed: dpnp.float_power of an int8 array returns float32, and dpnp.ldexp of a Python integer and an integer array returns float64, where NumPy returns float64 and float16; both also happen with small integers. dpnp.searchsorted(x, 2**64) now raises OverflowError, where NumPy returns len(x).

Performance against master on an Intel Data Center GPU Max 1100 (Level Zero) and a Xeon Platinum 8480+ (OpenCL CPU device), n = 1 / 4096 / 2**24 elements, 8 rounds of fresh processes in alternating order:

Case GPU CPU
Python scalar the kernel reads natively: add, less, equal, logical_and, divide, x += 1 no change no change
Scalar that needed a cast: arctan2(i4, 2), hypot(i8, 3), divide(i4, 2), divide(b1, 2) about 10 % faster (20-40 µs per call) at n ≤ 4096, no change at 2**24 no change
logical_and(b1, 1) 2.3x / 2.1x / 1.6x faster 1.9x / 1.8x / 7.5x faster
less(i4, 2**64), less(2**64, i4), equal(i8, -2**64) (raised before) 1.1-1.3x / 1.1x / 1.0x the time of the in-range comparison 1.0x the time of the in-range comparison

"No change" means within the run-to-run variation of untouched code (GPU 3-9 %, CPU 3-49 %, largest at small n). At 2**24 on the GPU, the cases that make float64 temporaries vary by up to 50 % between processes on both master and this branch; their medians stay within 5 %. The added Python cost is 34 ns per binary call and up to 0.2 µs for a comparison, divide or logical function with a Python integer.

  • Have you provided a meaningful PR description?
  • Have you added a test, reproducer or referred to an issue with a reproducer?
  • Have you tested your changes locally for CPU and GPU devices?
  • Have you made sure that new changes do not introduce compiler warnings?
  • Have you checked performance impact of proposed changes?
  • Have you added documentation for your changes, if necessary?
  • Have you added your changes to the changelog?

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.
… 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.
…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.
@github-actions

Copy link
Copy Markdown
Contributor

View rendered docs @ https://intelpython.github.io/dpnp/pull/3202/index.html

@github-actions

Copy link
Copy Markdown
Contributor

Array API standard conformance tests for dpnp=0.22.0dev3=np2py314h8d9cdd5_60 ran successfully.
Passed: 1491
Failed: 0
Skipped: 6

@coveralls

Copy link
Copy Markdown
Collaborator

Coverage Status

coverage: 84.573% (+0.02%) from 84.553% — fix-out-of-range-py-int-in-binary-ufuncs into master

@vlad-perevezentsev vlad-perevezentsev left a comment

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.

I tested it on GPU and CPU: the new tests pass and fail on master, and comparisons, divide, the logical and floating-point functions now match NumPy for out-of-range integers. A few small comments below.

Comment on lines +903 to +919
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)

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?


"""

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.

Comment thread CHANGELOG.md
Comment on lines +62 to +63
* 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)

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants