Skip to content

Fix six NumPy mismatches in tf.experimental.numpy - #129241

Merged
copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix-tnp-numpy-compat
Oct 23, 2026
Merged

copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix-tnp-numpy-compat

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

Fixes #129232, fixes #129233, fixes #129236, fixes #129237, fixes #129238, fixes #129239.

These are six places where tf.experimental.numpy gives a different answer than NumPy, or raises where NumPy doesn't. They don't depend on each other, but they all live in np_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 for decimals=-1 was really 0.10000000149. That's enough to push 2.5 over to 3 before rounding: around(25, -1) gave 29 and around(5, -1) gave 9.

The factor is now created with constant_op.constant directly in the working dtype. For negative decimals it divides by 10**-decimals instead of multiplying by 10**decimals, which is what NumPy does (10 is exact in binary, 0.1 isn't). Integer inputs with decimals >= 0 are returned unchanged. There's nothing to round, and the round trip through float64 was corrupting values above 2**53.

trace (#129233)

The offset=0 shortcut called math_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. diagonal already takes the matrix_diag_part fast path for the last two axes, so what's left is matrix_diag_part followed by sum, and sum does the same promotion as NumPy.

geomspace (#129236)

Two changes. First, the endpoints are now set to exactly start and stop after the logspace call, 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 how geomspace(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 pow per endpoint.

float_power (#129237)

This was just an alias for power, so ints stayed ints and float_power(2, -1) raised "Integers to negative integer powers are not allowed". It now casts both operands to result_type(float), or result_type(complex) for complex input, before calling power. That's float64/complex128 unless float64 has been disabled.

rad2deg (#129238)

It now goes through _scalar(..., promote_to_float=True) like deg2rad does, so lists, integer arrays and NumPy arrays all work and come back as tensors.

cumsum / cumprod (#129239)

_maybe_promote_to_int now treats bool like a narrow integer type, so bool input accumulates as int64, the same way tnp.sum and tnp.prod already handle it.

Testing

I added tests for each fix to np_math_ops_test.py and np_array_ops_test.py, and added rad2deg to the list in np_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.py
  • np_array_ops_test.py
  • both *_no_numpy_methods_test.py files
  • the float_power, rad2deg, geomspace, cumsum, cumprod, round and trace cases from tests/np_test.py

Everything passes except ArrayMethodsTest.testRoll. That test fails the same way on unmodified master with this nightly, so it's not related to this change.

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Oct 17, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 17, 2026 17:36
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 17, 2026

@gemini-code-assist gemini-code-assist Bot 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.

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.

@nithyak0204 nithyak0204 self-assigned this Oct 19, 2026
@nithyak0204
nithyak0204 requested a review from a team October 19, 2026 05:16
@nithyak0204 nithyak0204 added comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Oct 19, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 19, 2026

@dmiltr3 dmiltr3 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.

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_dtype is narrower than float64 (np.float32 for abs(decimals) > 38, np.float16 for abs(decimals) > 4, or integer inputs when prefer_float32 / allow_float64=False is enabled), math.pow(10, abs(decimals)) returns a finite Python float that overflows float_dtype, causing constant_op.constant(..., float_dtype) to raise ValueError: Cannot convert ... to EagerTensor of dtype float32 (or float16). For negative decimals such as around(np.float32(2.5), -40) or around(np.float16(2.5), -5), this regresses from master where 10**decimals < 1.0 did not overflow.
  • Even for float64, clamping decimals > 308 to 308 still multiplies a by 1e308, which overflows a * factor to inf whenever abs(a) >= 1.8 (for example, around(2.0, 400) returns inf instead of 2.0). Similarly, clamping decimals < -308 to -308 causes around(1.2e308, -400) to return 1e308 instead of 0.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.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 19, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Pushed an update checking decimals against each float type's max exponent, expanded testAroundHugeDecimals, and included -1 in testAroundAcceptsIntegerInputs.

@dmiltr3 dmiltr3 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.

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.
@dmiltr3
dmiltr3 force-pushed the fix-tnp-numpy-compat branch from 43263e0 to 1904a28 Compare October 23, 2026 08:13
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Oct 23, 2026
@dmiltr3 dmiltr3 added the ready to pull PR ready for merge process label Oct 23, 2026
@nithyak0204 nithyak0204 removed the ready to pull PR ready for merge process label Oct 23, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 October 23, 2026 08:24
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 23, 2026
@copybara-service
copybara-service Bot merged commit a67343d into tensorflow:master Oct 23, 2026
15 of 17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 23, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Oct 23, 2026
@nithyak0204
nithyak0204 removed the request for review from dmiltr3 October 23, 2026 13:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment