Skip to content

Fix isclose/allclose returning inverted results for infinities - #128483

Merged
copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
genius-0963:fix-isclose-infinity-handling
Oct 15, 2026
Merged

copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
genius-0963:fix-isclose-infinity-handling

Conversation

@genius-0963

@genius-0963 genius-0963 commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #128480

tf.experimental.numpy.isclose and allclose return inverted results for infinities compared to NumPy, and also incorrectly return True for mixed finite/infinite pairs.

Root Cause

The floating-point branch applies the finite tolerance formula directly:

result = math_ops.abs(a - b) <= atol_ + rtol_ * math_ops.abs(b)

For non-finite values this breaks in three ways:

Case Formula evaluates to Correct
inf vs inf (same-sign) abs(NaN) <= ... → False True
-inf vs inf (opposite-sign) inf <= inf → True False
1.0 vs inf (mixed) inf <= inf → True False

Fix

Use an is_finite mask instead of where_v2:

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)

This ensures:

  • Finite pairs: use the tolerance formula (masked by both_finite)
  • Same-sign infinities: pass via equal(a, b)
  • Opposite-sign or mixed: fail both branches → False

For complex types, is_finite is checked on the real and imaginary parts directly rather than computing magnitude via abs(a), avoiding magnitude overflow to inf for large finite values (e.g., np.complex64(3e38+3e38j)). The equal_nan block is also fixed for complex types by checking is_nan on real/imag parts separately, avoiding a missing kernel crash.

Tests

  • testIsCloseInfinities parameterized over float32, float64, complex64, complex128 covering:
    • Same-sign infinities (inf/inf, -inf/-inf)
    • Opposite-sign infinities (-inf/inf, inf/-inf)
    • Mixed finite/infinite (1.0/inf, inf/1.0)
    • Symmetric complex infinities ((inf+infj)/(inf+0j), (inf+0j)/(inf+infj), (inf+infj)/(inf+infj))
    • allclose permutations: [inf]/[inf], [-inf]/[inf], [inf]/[-inf], and [-inf]/[-inf]
  • testIsCloseEqualNan parameterized over floating and complex dtypes covering real, imag, and mixed NaN components.
  • testIsCloseIntegerTolerances covering integer tolerance handling without graph-mode bool() evaluation.

Before (broken)

TensorFlow isclose: [False, False, True, True, True]
NumPy isclose:      [True, True, False, False, True]
isclose(1.0, inf):  True  (should be False)

After (fixed)

TensorFlow isclose: [True, True, False, False, True]
NumPy isclose:      [True, True, False, False, True]
isclose(1.0, inf):  False ✓

@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Oct 4, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 4, 2026 13:02
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 4, 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 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 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.

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))

@genius-0963
genius-0963 force-pushed the fix-isclose-infinity-handling branch 2 times, most recently from 1659ba0 to 08f0f15 Compare October 5, 2026 12:18
@genius-0963

Copy link
Copy Markdown
Contributor Author

Addressing Review Feedback

Thank you for the thorough review @dmiltr3! All three requested changes have been addressed in the latest push.

Summary of the Fix

The 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:

Case What Happens Expected
inf vs inf abs(NaN) <= ... → False True
-inf vs inf inf <= inf → True False
1.0 vs inf inf <= inf → True False

The Fix (Lines 604–623)

Replaced the simple formula with proper infinity handling using is_finite masking:

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:

  • ✅ Finite pairs: Use the tolerance formula (masked by both_finite)
  • ✅ Same-sign infinities: Pass via equal(a, b) → True
  • ✅ Opposite-sign or mixed pairs: Fail both branches → False
  • ✅ Complex types: Handle via magnitude checks and separate real/imag NaN tests

Changes Made

  1. Mixed finite/infinite fix — Replaced where_v2-based approach with is_finite masking, avoiding graph overhead on the fast path
  2. Expanded test coverage — testIsCloseInfinities now parameterizes over float32, float64, complex64, complex128 with mixed finite/infinite pairs and complex infinity values
  3. Complex equal_nan fix — is_nan applied to real()/imag() parts separately for complex types, avoiding the missing C++ kernel crash

Note: The CI failures in the previous run were all self-hosted runner infrastructure issues (Executing the custom container implementation failed) — none reached the build/test phase.

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
@genius-0963
genius-0963 force-pushed the fix-isclose-infinity-handling branch from 08f0f15 to aa9cb3d Compare October 6, 2026 12:23

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

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))

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Oct 8, 2026
…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.
@genius-0963

Copy link
Copy Markdown
Contributor Author

Review, sir

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Oct 11, 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.

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.
@genius-0963

Copy link
Copy Markdown
Contributor Author

Review, sir

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

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:

  1. 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.

  2. Asymmetric Test Coverage for Infinities: The testIsCloseInfinities method lacks symmetric coverage for complex mixed cases and allclose permutations. It tests (inf+infj, inf+0j) but omits the reverse, and allclose validates [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
@genius-0963

Copy link
Copy Markdown
Contributor Author

review

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

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.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 13, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 13, 2026
@nithyak0204 nithyak0204 removed the kokoro:force-run Tests on submitted change label Oct 14, 2026
@genius-0963

Copy link
Copy Markdown
Contributor Author

@cantonios sir, please reviw

@copybara-service
copybara-service Bot merged commit e017294 into tensorflow:master Oct 15, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:ops OPs related issues prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.experimental.numpy.isclose and allclose return inverted results for infinities

4 participants