Repository navigation
Fix isclose/allclose returning inverted results for infinities - #128483
copybara-service[bot] merged 5 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request fixes an issue in np_math_ops.isclose where infinities were not handled correctly, causing inverted results compared to NumPy. It introduces a separate handling mechanism for infinities and adds a corresponding regression test. The review feedback suggests making the infinity handling more robust by guarding against non-floating/non-complex types to avoid TypeError and expanding the test suite to cover complex number types.
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the fix. While this correctly addresses pairs of infinities, we need a few adjustments to correctly handle mixed finite/infinite pairs, avoid unnecessary overhead on the fast path, and ensure comprehensive test coverage.
1. Fix Mixed Finite/Infinite Comparisons and Fast-Path Overhead
Currently, the implementation falls back to the tolerance formula when one operand is finite and the other is infinite (e.g., 1.0 and inf). The formula abs(1.0 - inf) <= atol + rtol * abs(inf) simplifies to inf <= inf, which evaluates to True in TensorFlow. Consequently, isclose(1.0, np.inf) incorrectly returns True.
Additionally, evaluating math_ops.abs(a) for real floating-point tensors and using where_v2 adds unnecessary graph overhead to the green path. We can resolve the mixed-pair bug and optimize the fast path by masking the tolerance formula using is_finite and simple bitwise logic.
Please update tensorflow/python/ops/numpy_ops/np_math_ops.py (around line 604):
rtol_ = ops.convert_to_tensor(rtol, dtype.real_dtype)
atol_ = ops.convert_to_tensor(atol, dtype.real_dtype)
b_abs = math_ops.abs(b)
result = math_ops.abs(a - b) <= atol_ + rtol_ * b_abs
# Infinities must be handled separately. The finite tolerance formula
# evaluates to True for mixed finite/infinite pairs like (1.0, inf)
# because inf <= inf. Match NumPy: elements are close if they are
# both finite and within tolerance, or if they are equal.
if dtype.is_floating or dtype.is_complex:
if dtype.is_complex:
a_check = math_ops.abs(a)
b_check = b_abs
else:
a_check = a
b_check = b
both_finite = math_ops.is_finite(a_check) & math_ops.is_finite(b_check)
result = (both_finite & result) | math_ops.equal(a, b)2. Test Coverage for Complex Infinities and Mixed Pairs
The test needs to cover the boundary conditions for finite vs inf, as well as infinite complex values, to guarantee correctness across all paths.
Please expand testIsCloseInfinities in tensorflow/python/ops/numpy_ops/np_math_ops_test.py:
@parameterized.parameters([np.float32, np.float64, np.complex64, np.complex128])
def testIsCloseInfinities(self, dtype):
a_vals = [np.inf, -np.inf, -np.inf, np.inf, 1.0, 1.0, np.inf]
b_vals = [np.inf, -np.inf, np.inf, -np.inf, 1.0, np.inf, 1.0]
if np.issubdtype(dtype, np.complexfloating):
a_vals.extend([complex(np.inf, np.inf), complex(np.inf, np.inf)])
b_vals.extend([complex(np.inf, 0), complex(np.inf, np.inf)])
a = np.array(a_vals, dtype)
b = np.array(b_vals, dtype)
self.match(
np_math_ops.isclose(a, b),
np.isclose(a, b),
)
self.assertEqual(
bool(np_math_ops.allclose([dtype(np.inf)], [dtype(np.inf)])),
np.allclose([dtype(np.inf)], [dtype(np.inf)]),
)
self.assertEqual(
bool(np_math_ops.allclose([dtype(-np.inf)], [dtype(np.inf)])),
np.allclose([dtype(-np.inf)], [dtype(np.inf)]),
)3. (Optional / Pre-existing Defect) Handle Complex Types in equal_nan
There is a pre-existing defect in the equal_nan=True block: math_ops.is_nan lacks a C++ kernel for complex types, which means isclose(..., equal_nan=True) will crash for complex inputs. We highly recommend fixing this alongside your changes.
In tensorflow/python/ops/numpy_ops/np_math_ops.py (around line 614):
if equal_nan:
if dtype.is_complex:
a_nan = math_ops.is_nan(math_ops.real(a)) | math_ops.is_nan(math_ops.imag(a))
b_nan = math_ops.is_nan(math_ops.real(b)) | math_ops.is_nan(math_ops.imag(b))
result = result | (a_nan & b_nan)
else:
result = result | (math_ops.is_nan(a) & math_ops.is_nan(b))1659ba0 to
08f0f15
Compare
Addressing Review FeedbackThank you for the thorough review @dmiltr3! All three requested changes have been addressed in the latest push. Summary of the FixThe error was in the tolerance formula at line 604: result = math_ops.abs(a - b) <= atol_ + rtol_ * math_ops.abs(b)This formula fails for non-finite values in three critical ways:
The Fix (Lines 604–623)Replaced the simple formula with proper infinity handling using b_abs = math_ops.abs(b)
result = math_ops.abs(a - b) <= atol_ + rtol_ * b_abs
# Use is_finite mask to handle infinities separately
both_finite = math_ops.is_finite(a_check) & math_ops.is_finite(b_check)
result = (both_finite & result) | math_ops.equal(a, b)This ensures:
Changes Made
|
The floating-point branch of tf.experimental.numpy.isclose applied the finite tolerance formula |a - b| <= atol + rtol * |b| directly to all values including infinities. This produced wrong results: - Same-sign: inf - inf = NaN, abs(NaN) <= ... is False (should be True) - Opposite-sign: abs(-inf - inf) = inf, inf <= inf is True (should be False) - Mixed finite/inf: abs(1.0 - inf) = inf, inf <= inf is True (should be False) Replace the previous where_v2-based infinity fix with an is_finite mask approach: the tolerance result is AND-ed with both_finite so only finite-finite pairs use the formula, then OR-ed with equality so identical infinities (same sign) are still close. This avoids the where_v2 overhead on the fast path. For complex types, is_finite and is_nan are applied to the magnitude or real/imag parts respectively, since these ops lack complex kernels. Add testIsCloseInfinities regression test parameterized over float32, float64, complex64, and complex128, covering element-wise isclose and scalar allclose with same-sign, opposite-sign, mixed finite/infinite, and complex infinite pairs. Fixes tensorflow#128480
08f0f15 to
aa9cb3d
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: The previous snippet for handling complex types in both_finite calculated a_check = math_ops.abs(a). For extreme but finite complex values (e.g. np.complex64(3e38+3e38j)), abs() overflows into inf. This causes is_finite() to falsely report False, diverging from NumPy's behavior. We must check is_finite on the real and imag parts instead of abs().
Thank you for the fix. This correctly addresses pairs of infinities, mixed finite/infinite pairs, and complex NaN comparisons by separating the finite and equality paths. However, there are a few issues to address regarding complex finiteness, testing in graph mode, and missing coverage for the new complex equal_nan path.
1. Avoid magnitude overflow for complex finiteness
As noted in the correction above, using math_ops.abs(a) for complex inputs computes the magnitude, which overflows to inf for large finite complex values (e.g., np.complex64(3e38 + 3e38j)). When this happens, both_finite incorrectly evaluates to False, forcing the code into a strict equality fallback and diverging from NumPy. We should check is_finite on the real and imaginary parts directly.
Please update tensorflow/python/ops/numpy_ops/np_math_ops.py (around line 612):
if dtype.is_floating or dtype.is_complex:
if dtype.is_complex:
both_finite = (
math_ops.is_finite(math_ops.real(a))
& math_ops.is_finite(math_ops.imag(a))
& math_ops.is_finite(math_ops.real(b))
& math_ops.is_finite(math_ops.imag(b))
)
else:
both_finite = math_ops.is_finite(a) & math_ops.is_finite(b)
result = (both_finite & result) | math_ops.equal(a, b)2. Graph mode compatibility in test assertions
In testIsCloseInfinities, calling bool(np_math_ops.allclose(...)) directly on the returned Tensor will crash with TypeError: __bool__ is not allowed for Tensor when the test executes in graph mode. Use self.match(...) instead, which properly evaluates the tensor across execution modes (standard practice in numpy_ops tests).
Please update tensorflow/python/ops/numpy_ops/np_math_ops_test.py (around line 405):
self.match(
np_math_ops.allclose([dtype(np.inf)], [dtype(np.inf)]),
np.allclose([dtype(np.inf)], [dtype(np.inf)]),
)
self.match(
np_math_ops.allclose([dtype(-np.inf)], [dtype(np.inf)]),
np.allclose([dtype(-np.inf)], [dtype(np.inf)]),
)3. Test coverage for complex equal_nan path
The PR added a complex-specific path to handle equal_nan=True (np_math_ops.py:623-630) to avoid a missing complex kernel crash in is_nan, but left the corresponding test testIsCloseEqualNan hardcoded to np.float32 only. Every new branch must have a deterministic test that reaches it.
Please parameterize testIsCloseEqualNan in tensorflow/python/ops/numpy_ops/np_math_ops_test.py (around line 378) to cover floating and complex types, including complex numbers with NaN in either component:
@parameterized.parameters(
itertools.product(
[False, True],
[np.float32, np.float64, np.complex64, np.complex128]
)
)
def testIsCloseEqualNan(self, equal_nan, dtype):
a_vals = [1.0, 1.0, np.nan, 1.0, np.nan]
b_vals = [1.0, 2.0, 1.0, np.nan, np.nan]
if np.issubdtype(dtype, np.complexfloating):
a_vals.extend([
complex(1.0, np.nan),
complex(np.nan, 1.0),
complex(np.nan, np.nan),
])
b_vals.extend([
complex(np.nan, 1.0),
complex(1.0, np.nan),
complex(np.nan, np.nan),
])
a = np.asarray(a_vals, dtype)
b = np.asarray(b_vals, dtype)
self.match(
np_math_ops.isclose(a, b, equal_nan=equal_nan),
np.isclose(a, b, equal_nan=equal_nan))…rage - Check is_finite on real/imag parts instead of abs() to avoid magnitude overflow for large finite complex values (e.g. np.complex64(3e38+3e38j)) - Replace bool(tensor) with self.match() in testIsCloseInfinities for graph-mode compatibility - Parameterize testIsCloseEqualNan over float and complex dtypes with NaN in real, imag, and both components
np.allclose returns a python bool rather than an ndarray, which lacks dtype and shape attributes and caused AttributeError in match. Converting expected with np.asarray ensures match handles both array and scalar/bool results.
|
Review, sir |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates. The implementation correctly handles infinities and mixed finite/infinite pairs in isclose and allclose, avoids magnitude overflow for complex numbers by checking real and imaginary parts directly, and provides robust test coverage across all inexact dtypes in both testIsCloseEqualNan and testIsCloseInfinities. However, there is one remaining instance of the graph-mode crash pattern in the tests.
1. Fix graph-mode compatibility in testIsCloseIntegerTolerances
While the bool(...) wrappers on allclose were correctly removed in testIsCloseInfinities, the identical anti-pattern remains in testIsCloseIntegerTolerances. Calling bool(...) on a Tensor crashes in graph mode (TypeError: __bool__ is not allowed for Tensor).
Please update tensorflow/python/ops/numpy_ops/np_math_ops_test.py (around line 445) to use self.match():
self.match(
np_math_ops.allclose(a, b, rtol=9, atol=0),
np.allclose(a, b, rtol=9, atol=0),
)…tibility Replace bool(...) call on allclose with self.match(...) to prevent TypeError in graph execution mode.
|
Review, sir |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for updating the pull request to fix the graph-mode test assertion issue and thoroughly testing infinities and mixed finite/infinite pairs across floating-point and complex data types. The implementation correctly matches NumPy behavior without introducing hot-path overhead.
There are a couple of remaining issues:
-
Stale Description Mismatch: The PR description still states "For complex types, is_finite is applied to the magnitude (
abs(a)) since it lacks a complex kernel." However, the code correctly checks the real and imaginary parts separately to avoid magnitude overflow for large finite values. Please update the PR description to accurately reflect the final implementation. -
Asymmetric Test Coverage for Infinities: The
testIsCloseInfinitiesmethod lacks symmetric coverage for complex mixed cases andallclosepermutations. It tests(inf+infj, inf+0j)but omits the reverse, andallclosevalidates[inf], [inf]and[-inf], [inf], but misses the symmetric[inf], [-inf]and same-negative[-inf], [-inf]edge cases.
Please update tensorflow/python/ops/numpy_ops/np_math_ops_test.py around line 414 to:
if np.issubdtype(dtype, np.complexfloating):
a_vals.extend([
complex(np.inf, np.inf), complex(np.inf, np.inf), complex(np.inf, 0)
])
b_vals.extend([
complex(np.inf, 0), complex(np.inf, np.inf), complex(np.inf, np.inf)
])And update the allclose checks around line 424 to:
self.match(
np_math_ops.allclose([dtype(np.inf)], [dtype(np.inf)]),
np.allclose([dtype(np.inf)], [dtype(np.inf)]),
)
self.match(
np_math_ops.allclose([dtype(-np.inf)], [dtype(np.inf)]),
np.allclose([dtype(-np.inf)], [dtype(np.inf)]),
)
self.match(
np_math_ops.allclose([dtype(np.inf)], [dtype(-np.inf)]),
np.allclose([dtype(np.inf)], [dtype(-np.inf)]),
)
self.match(
np_math_ops.allclose([dtype(-np.inf)], [dtype(-np.inf)]),
np.allclose([dtype(-np.inf)], [dtype(-np.inf)]),
)- Add reverse test pair (inf+0j, inf+infj) for complex isclose - Add [inf], [-inf] and [-inf], [-inf] cases for allclose
|
review |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The pull request perfectly incorporates all of the requested feedback. The implementation elegantly solves the mixed-pairs bug, properly safeguards complex finiteness checks against magnitude overflow, and correctly avoids graph-mode execution exceptions in the test assertions. Your test coverage is very thorough across all data types and edge permutations.
We appreciate your contributions to improving TensorFlow's mathematical consistency with NumPy. This change looks solid and is approved to merge.
|
@cantonios sir, please reviw |
Description
Fixes #128480
tf.experimental.numpy.iscloseandallclosereturn inverted results for infinities compared to NumPy, and also incorrectly returnTruefor mixed finite/infinite pairs.Root Cause
The floating-point branch applies the finite tolerance formula directly:
For non-finite values this breaks in three ways:
infvsinf(same-sign)abs(NaN) <= ...→ False-infvsinf(opposite-sign)inf <= inf→ True1.0vsinf(mixed)inf <= inf→ TrueFix
Use an
is_finitemask instead ofwhere_v2:This ensures:
both_finite)equal(a, b)FalseFor complex types,
is_finiteis checked on the real and imaginary parts directly rather than computing magnitude viaabs(a), avoiding magnitude overflow toinffor large finite values (e.g.,np.complex64(3e38+3e38j)). Theequal_nanblock is also fixed for complex types by checkingis_nanon real/imag parts separately, avoiding a missing kernel crash.Tests
testIsCloseInfinitiesparameterized overfloat32,float64,complex64,complex128covering:inf/inf,-inf/-inf)-inf/inf,inf/-inf)1.0/inf,inf/1.0)(inf+infj)/(inf+0j),(inf+0j)/(inf+infj),(inf+infj)/(inf+infj))allclosepermutations:[inf]/[inf],[-inf]/[inf],[inf]/[-inf], and[-inf]/[-inf]testIsCloseEqualNanparameterized over floating and complex dtypes covering real, imag, and mixed NaN components.testIsCloseIntegerTolerancescovering integer tolerance handling without graph-modebool()evaluation.Before (broken)
After (fixed)