Repository navigation
BUG: torch: accept Python scalars in binary elementwise functions - #478
raashish1601 wants to merge 1 commit into
Conversation
torch.maximum, minimum, atan2, hypot, logaddexp, nextafter and the logical functions reject Python scalars, and the comparisons and copysign reject a scalar as the first argument. Convert the scalar to a 0-D tensor of the result dtype in these positions. Closes data-apis#271
I'd suggest that it's not worth the extra complexity to figure out precisely when torch rejects scalars and use |
There was a problem hiding this comment.
IIUC, there are two tests (conceptually) that we want to perform for all these functions:
- check that passing in one array and one scalar produces the same output as if the scalar had been passed in as an array of the correct dtype.
- check that passing in two scalars raises an error.
So I think one function could perform the first test, parametrized over all the dtypes accepted by each function, and a second function could perform a simpler check for the error.
(Or, personally, I would just as well ignore the requirement that one argument must be an array. NumPy functions don't care, and torch.result_type is happy with two scalars, so why shouldn't these two-arg functions accept two scalars, too? This would eliminate the artificial requirement of checking for Python scalars/raising and for the second test.)
Closes #271 (also covers #410).
torch.maximum,minimum,atan2,hypot,logaddexp,nextafterandlogical_and/or/xorreject Python scalars, andequal,not_equal,less,less_equal,greater,greater_equalandcopysignreject a scalar as the first argument. The 2024.12 standard allows a scalar in either position.Following the idea in the issue,
_two_argnow takesscalar_x1/scalar_x2flags. When set, a Python scalar in that position is converted to a 0-D tensor withresult_type(scalar, other)on the other argument's device. The flags are only set where torch rejects the scalar, so calls that already work (e.g.add(x, 1)) take the same path as before.nextafterand the logical functions are now wrapped too and added to__all__.Testing: removed the matching
test_binary_with_scalars_*entries fromtorch-xfails.txt; those 28 tests pass locally against array-api-tests, along with the rest oftest_operators_and_elementwise_functions.pyandtest_signatures.py. Added tests totests/test_torch.py; they fail on main and pass with this change.ruff check .passes.