Repository navigation
Fix six NumPy mismatches in tf.experimental.numpy - #129241
copybara-service[bot] merged 4 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves NumPy compatibility in TensorFlow's numpy_ops by refining dtype promotion (e.g., for booleans in cumulative operations and trace), enhancing precision in around and geomspace (using a Newton step correction for log10), and updating float_power and rad2deg. Review feedback recommends clipping decimals in around to prevent OverflowError with extremely large values, extending the _geomspace_log10 dtype check to include complex types, and casting endpoints in geomspace to res.dtype to avoid runtime DtypeMismatch errors during concatenation.
dmiltr3
left a comment
There was a problem hiding this comment.
1. Handle out-of-range decimals per floating-point dtype in around without scaling at the clamped bound
In tensorflow/python/ops/numpy_ops/np_array_ops.py:978-984, decimals is clamped to [-308, 308] (the float64 exponent limit) and then a is multiplied or divided by constant_op.constant(math.pow(10, abs(decimals)), float_dtype):
- When
float_dtypeis narrower thanfloat64(np.float32forabs(decimals) > 38,np.float16forabs(decimals) > 4, or integer inputs whenprefer_float32/allow_float64=Falseis enabled),math.pow(10, abs(decimals))returns a finite Pythonfloatthat overflowsfloat_dtype, causingconstant_op.constant(..., float_dtype)to raiseValueError: Cannot convert ... to EagerTensor of dtype float32(orfloat16). For negativedecimalssuch asaround(np.float32(2.5), -40)oraround(np.float16(2.5), -5), this regresses frommasterwhere10**decimals < 1.0did not overflow. - Even for
float64, clampingdecimals > 308to308still multipliesaby1e308, which overflowsa * factortoinfwheneverabs(a) >= 1.8(for example,around(2.0, 400)returnsinfinstead of2.0). Similarly, clampingdecimals < -308to-308causesaround(1.2e308, -400)to return1e308instead of0.0.
Instead of clamping decimals and running the multiply/divide scaling at the boundary, please check decimals against the maximum base-10 exponent of float_dtype (4 for float16, 38 for bfloat16 and float32, 308 for float64), returning math_ops.cast(a, dtype) when decimals > max_decimals and array_ops.zeros_like(a, dtype=dtype) when decimals < -max_decimals:
_AROUND_MAX_DECIMALS = {
dtypes.float16: 4,
dtypes.bfloat16: 38,
dtypes.float32: 38,
dtypes.float64: 308,
}
@tf_export.tf_export('experimental.numpy.around', v1=[])
@np_utils.np_doc('around')
def around(a, decimals=0): # pylint: disable=missing-docstring
a = asarray(a)
dtype = a.dtype.as_numpy_dtype
if a.dtype.is_integer and decimals >= 0:
# Integers are already rounded to any non-negative number of decimals.
# Going through a float dtype would also lose precision above 2**53.
return a
if np.issubdtype(dtype, np.inexact):
float_dtype = dtype
else:
# Use float as the working dtype when a.dtype is exact (e.g. integer),
# because `decimals` can be negative.
float_dtype = np_utils.result_type(float)
# `Tensor.astype` only exists once `enable_numpy_methods_on_tensor()`
# has been called, and is an alias of `math_ops.cast`; calling `cast`
# directly keeps `around` working without that opt-in.
a = math_ops.cast(a, float_dtype)
max_decimals = _AROUND_MAX_DECIMALS.get(
dtypes.as_dtype(float_dtype).real_dtype, 308
)
if decimals > max_decimals:
return math_ops.cast(a, dtype)
if decimals < -max_decimals:
return array_ops.zeros_like(a, dtype=dtype)
factor = constant_op.constant(math.pow(10, abs(decimals)), float_dtype)
if decimals >= 0:
a = math_ops.divide(math_ops.round(math_ops.multiply(a, factor)), factor)
else:
a = math_ops.multiply(math_ops.round(math_ops.divide(a, factor)), factor)
return math_ops.cast(a, dtype)Please also expand testAroundHugeDecimals in tensorflow/python/ops/numpy_ops/np_array_ops_test.py:1276-1282 to cover 2.0 (where 2.0 * 1e308 would overflow float64), 1.2e308 with decimals=-400, and float32 / float16 inputs with out-of-range exponents:
def testAroundHugeDecimals(self):
# `decimals` beyond the float exponent range must not overflow the
# scale factor or intermediate product.
for val in (1.5, 2.0):
self.assertEqual(float(np_array_ops.around(val, 400)), val)
self.assertEqual(float(np_array_ops.around(val, -400)), 0.0)
self.assertEqual(float(np_array_ops.around(1.2e308, -400)), 0.0)
self.assertEqual(int(np_array_ops.around(np.int64(12345), -400)), 0)
for dtype, exp in ((np.float32, 40), (np.float16, 5)):
x = dtype(2.5)
self.assertEqual(float(np_array_ops.around(x, exp)), 2.5)
self.assertEqual(float(np_array_ops.around(x, -exp)), 0.0)2. Keep the integer-to-float promotion branch covered in testAroundAcceptsIntegerInputs
In tensorflow/python/ops/numpy_ops/np_array_ops_no_numpy_methods_test.py:48-61, testAroundAcceptsIntegerInputs only iterates over for decimals in (0, 1):. Because around now returns integer inputs early when decimals >= 0, that loop no longer reaches the integer-to-float promotion branch (tensorflow/python/ops/numpy_ops/np_array_ops.py:963-970) that the test was written to exercise without enable_numpy_methods_on_tensor(). Please include -1 (for decimals in (-1, 0, 1): at tensorflow/python/ops/numpy_ops/np_array_ops_no_numpy_methods_test.py:55) so both paths remain covered.
|
Pushed an update checking decimals against each float type's max exponent, expanded testAroundHugeDecimals, and included -1 in testAroundAcceptsIntegerInputs. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for addressing the feedback from the previous round. Both updates—bounding decimals per floating-point dtype via _AROUND_MAX_DECIMALS in tensorflow/python/ops/numpy_ops/np_array_ops.py (with expanded coverage in testAroundHugeDecimals in tensorflow/python/ops/numpy_ops/np_array_ops_test.py) and including -1 in testAroundAcceptsIntegerInputs in tensorflow/python/ops/numpy_ops/np_array_ops_no_numpy_methods_test.py—look good. The changes are ready to merge.
- around: build the scale factor directly in the working dtype and divide by 10**-decimals for negative decimals, as NumPy does. The old math_ops.cast(0.1, float64) went through float32, so around(25, -1) returned 29 and around(5, -1) returned 9. Integers with decimals >= 0 are now returned unchanged instead of round-tripping through float64. - trace: drop the math_ops.trace shortcut, which summed in the input dtype. int8/uint8 inputs overflowed and bool inputs raised; the diagonal + sum path promotes like np.trace. - geomspace: pin the endpoints to start/stop like NumPy and refine the endpoint log10 with one Newton step, so integer dtypes no longer truncate 999.99... to 999. - float_power: compute in float64/complex128 (or the default float type when float64 is disabled) instead of aliasing power, so integers can take negative exponents. - rad2deg: convert and promote the input like deg2rad, so lists and integer arrays work. - cumsum/cumprod: promote bool inputs to int, matching NumPy and tnp.sum/tnp.prod. Fixes tensorflow#129232 Fixes tensorflow#129233 Fixes tensorflow#129236 Fixes tensorflow#129237 Fixes tensorflow#129238 Fixes tensorflow#129239
- around: clip decimals to [-308, 308] before computing 10**abs(decimals), which otherwise raised OverflowError for |decimals| >= 309. - geomspace: cast start/stop to the result dtype before concatenating the pinned endpoints. - _geomspace_log10: say in the docstring that only real floating-point inputs are refined (is_finite has no complex kernel).
geomspace(3, 3e5, 6, dtype=int64) is [3, 29, 300, ...] in NumPy, a truncation artifact of 29.999..., and tnp matched that on CPU but got 30 on GPU, which failed np_math_ops_test_gpu. Keep the integer-dtype cases to exact powers of ten and check the broadcast case in float.
Avoid multiplying or dividing by scale factors that overflow the working floating-point type when decimals exceeds the type's exponent range. Also expand huge decimals tests and include negative decimals in the integer promotion test.
43263e0 to
1904a28
Compare
a67343d
into
tensorflow:master
Fixes #129232, fixes #129233, fixes #129236, fixes #129237, fixes #129238, fixes #129239.
These are six places where
tf.experimental.numpygives a different answer than NumPy, or raises where NumPy doesn't. They don't depend on each other, but they all live innp_math_ops.py/np_array_ops.py, so I put them in one PR. Happy to split it up if that's easier to review.around(#129232)math_ops.cast(0.1, tf.float64)converts the Python float to float32 first, so the scale factor fordecimals=-1was really 0.10000000149. That's enough to push 2.5 over to 3 before rounding:around(25, -1)gave 29 andaround(5, -1)gave 9.The factor is now created with
constant_op.constantdirectly in the working dtype. For negativedecimalsit divides by10**-decimalsinstead of multiplying by10**decimals, which is what NumPy does (10 is exact in binary, 0.1 isn't). Integer inputs withdecimals >= 0are returned unchanged. There's nothing to round, and the round trip through float64 was corrupting values above 2**53.trace(#129233)The
offset=0shortcut calledmath_ops.trace, which sums in the input dtype. The trace of a 200x200 int8 matrix of ones came out as -56, and bool input raised. I removed the shortcut.diagonalalready takes thematrix_diag_partfast path for the last two axes, so what's left ismatrix_diag_partfollowed bysum, andsumdoes the same promotion as NumPy.geomspace(#129236)Two changes. First, the endpoints are now set to exactly
startandstopafter thelogspacecall, same as NumPy. Second, the log10 of each endpoint gets one Newton step.log(x) / log(10)returns 2.9999999999999996 for 1000, and that error spreads to every interior sample, which is howgeomspace(1, 1000, 4, dtype=np.int32)ended up as[1, 9, 99, 999].To check the correction I swept 3672 start/stop/num/endpoint combinations and compared the results after an integer cast. Before this change 2562 of them disagreed with NumPy. Now 34 do, and since the endpoints are exact, all of those are in the interior samples. The correction only runs on the endpoints, so it adds one extra
powper endpoint.float_power(#129237)This was just an alias for
power, so ints stayed ints andfloat_power(2, -1)raised "Integers to negative integer powers are not allowed". It now casts both operands toresult_type(float), orresult_type(complex)for complex input, before callingpower. That's float64/complex128 unless float64 has been disabled.rad2deg(#129238)It now goes through
_scalar(..., promote_to_float=True)likedeg2raddoes, so lists, integer arrays and NumPy arrays all work and come back as tensors.cumsum/cumprod(#129239)_maybe_promote_to_intnow treats bool like a narrow integer type, so bool input accumulates as int64, the same waytnp.sumandtnp.prodalready handle it.Testing
I added tests for each fix to
np_math_ops_test.pyandnp_array_ops_test.py, and addedrad2degto the list innp_math_ops_no_numpy_methods_test.py. All of the new tests fail on master.I ran these against tf-nightly 2.23.0-dev20261014 with the two source files swapped in:
np_math_ops_test.pynp_array_ops_test.py*_no_numpy_methods_test.pyfilesfloat_power,rad2deg,geomspace,cumsum,cumprod,roundandtracecases fromtests/np_test.pyEverything passes except
ArrayMethodsTest.testRoll. That test fails the same way on unmodified master with this nightly, so it's not related to this change.