Skip to content

Fix tf.experimental.numpy.isclose XLA shape mismatch - #122605

Closed
furk4neg3 wants to merge 3 commits into
tensorflow:masterfrom
furk4neg3:fix-numpy-allclose-xla-shape
Closed

furk4neg3 wants to merge 3 commits into
tensorflow:masterfrom
furk4neg3:fix-numpy-allclose-xla-shape

Conversation

@furk4neg3

@furk4neg3 furk4neg3 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #122052.

This change makes the non-inexact path of tf.experimental.numpy.isclose use strict TensorFlow equality for non-broadcastable inputs.

Tensor equality normally returns scalar False for incompatible shapes through the incompatible-shape fallback. Under jit_compile=True, the graph could still contain an Equal operation over incompatible shapes, causing XLA compilation to fail.

The non-inexact path now uses math_ops.equal, which applies strict broadcasting rules. As a result, non broadcastable inputs raise a ValueError or TensorFlow equivalent instead of returning False in eager execution and failing later during XLA compilation. This also keeps the behavior consistent with NumPy and with the existing inexact-type path.

The change is placed in isclose so that both direct isclose calls and allclose, which reduces the result of isclose, receive the fix.

The regression test covers both isclose and allclose with integer and floating-point inputs in eager and XLA-compiled execution.

Testing

bazel test --config=linux -k \
  //tensorflow/python/ops/numpy_ops:np_math_ops_test \
  --test_filter='*CloseNonBroadcastableShapesXla*'

bazel test --config=linux -k \
  //tensorflow/python/ops/numpy_ops:np_math_ops_test

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Jul 4, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios July 4, 2026 10:16
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 4, 2026
@furk4neg3
furk4neg3 force-pushed the fix-numpy-allclose-xla-shape branch from 4cc3140 to 05f3ffd Compare July 4, 2026 10:26
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@nithyak0204
nithyak0204 requested a review from a team July 6, 2026 11:12
@nithyak0204 nithyak0204 added comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Jul 6, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Jul 6, 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.

Feedback / Questions

  1. Input Types in Test Case: In the added test testAllCloseNonBroadcastableShapesXla, the tensor t is created with dtype=np.complex64. However, logical_xor converts its inputs to boolean anyway (_logical_binary_op explicitly casts to np.bool_). It might be slightly clearer to define t with a boolean or integer type directly to avoid confusion, though it works fine as is.
  2. Scope of Fix: The fix is added specifically to allclose. Have you considered whether a similar guard should be added to isclose as well, or if the current scope is sufficient? allclose calls isclose, so covering allclose fixes the most common failure path, but direct calls to isclose with non-broadcastable shapes might still diverge.
  3. Tolerance in Test: The test uses atol=-2.92515058314041. Note that for non-inexact types, isclose (and thus allclose) ignores atol and rtol and just checks equality (return a == b). The early return also skips this computation. Just something to keep in mind, as the negative value/precision has no effect on the test outcome for non-inexact dtypes.
  4. XLA Compiler Dependency: Running this test on CPU might fail with 'Could not find compiler for platform Host' if the XLA CPU JIT compiler is not linked in the test target/environment. Ensure the test environment has the necessary compiler linked or the test is targeted to run on GPU/TPU where applicable.

Overall, the logic is sound.

Proposed Unit Test

Here is the unit test we used to verify the fix:

  def testAllCloseNonBroadcastableShapesXla(self):
    import tensorflow as tf
    import numpy as np

    t = tf.convert_to_tensor(np.arange(8, dtype=np.complex64))

    def model(x):
      a = tf.experimental.numpy.hstack((5, 5, 5, 5))
      b = tf.experimental.numpy.logical_xor(x, x)
      return tf.experimental.numpy.allclose(a, b, atol=-2.92515058314041)

    eager_out = model(t)
    xla_out = tf.function(model, jit_compile=True)(t)

    self.assertAllEqual(eager_out, xla_out)
    self.assertAllEqual(False, xla_out)

Verification Results

We verified the fix using the provided test case under XLA compilation (jit_compile=True).

  • Eager Output: False
  • XLA Output: False
  • No XLA compilation errors observed for incompatible static shapes.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Jul 15, 2026
@furk4neg3 furk4neg3 changed the title Fix tf.experimental.numpy.allclose XLA shape mismatch Fix tf.experimental.numpy.isclose XLA shape mismatch Jul 16, 2026
@furk4neg3

Copy link
Copy Markdown
Contributor Author

Thanks for the review.

I moved the static broadcastability check from allclose into the non-inexact branch of isclose, where the incompatible equality operation is created. When the input shapes are statically known to be non-broadcastable, isclose now returns a scalar False before constructing the Equal operation that XLA cannot compile.

This also covers direct calls to isclose. allclose inherits the fix through its existing reduction of the result returned by isclose.

I also simplified the regression test to use direct integer tensors with shapes [4] and [8], removed the irrelevant negative atol, and parameterized the test to cover both isclose and allclose in eager and XLA-compiled execution.

Testing completed:

bazel test --config=linux -k \
  //tensorflow/python/ops/numpy_ops:np_math_ops_test \
  --test_filter='*CloseNonBroadcastableShapesXla*'

bazel test --config=linux -k \
  //tensorflow/python/ops/numpy_ops:np_math_ops_test

Both tests passed locally.

@furk4neg3
furk4neg3 requested a review from dmiltr3 July 16, 2026 09:05

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

We have reviewed your PR internally and verified the changes. Here is our recommendation for improving this fix to ensure consistency and compatibility.

Technical Review

1. Behavior of np.isclose with Non-Broadcastable Shapes

In your fix for np_math_ops.py, you added a check for broadcasting compatibility for integer/boolean dtypes:

      try:
        array_ops.broadcast_static_shape(a.shape, b.shape)
      except ValueError:
        return constant_op.constant(False)

While standard Python/NumPy equality comparisons (a == b) might return False for non-broadcastable shapes in some contexts, specialized functions like np.isclose are expected to follow strict broadcasting rules.

Consistency Issues:

  1. Divergence from NumPy: Standard NumPy's np.isclose raises a ValueError when operands cannot be broadcast, regardless of whether they are integers or floats. It does not return False.
  2. Internal Inconsistency: In your PR, this return False behavior is only applied to the else block (integers/bools). The if block (inexact/floats) still performs a - b. If shapes are non-broadcastable, a - b will raise a broadcasting error. This makes the function behave inconsistently depending on the dtype.

Best Approach

To maintain compatibility with NumPy and ensure internal consistency, isclose should raise or propagate a ValueError (or TF equivalent) when operand shapes are non-broadcastable, for all dtypes.

We recommend:

  • Removing the try-except block that returns False.
  • Allowing the broadcasting exception to propagate naturally (or raising a graceful Python ValueError after static shape validation if necessary to prevent raw compiler crashes).
  • Updating the corresponding test case testCloseNonBroadcastableShapesXla to expect this error/exception rather than asserting False.

Please let us know if you have any questions about this approach. We aim to keep tensorflow.experimental.numpy as faithful to standard NumPy semantics as possible.

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Jul 16, 2026
@furk4neg3

Copy link
Copy Markdown
Contributor Author

Thanks for the clarification. I updated the implementation to follow NumPy’s strict broadcasting behavior.

The non-inexact branch of isclose now uses math_ops.equal instead of Tensor operator equality. Tensor operator equality intentionally uses the incompatible-shape fallback and may return scalar False, while math_ops.equal performs strict broadcasting validation. Non-broadcastable inputs therefore raise a ValueError or TensorFlow equivalent instead of producing different eager and XLA behavior.

Because allclose reduces the result of isclose, it inherits the same behavior without requiring a separate implementation change.

I also updated the regression test to cover:

  • isclose and allclose
  • integer and floating-point inputs
  • eager and jit_compile=True execution
  • broadcasting-related exceptions rather than a scalar False result

Testing completed successfully:

bazel test --config=linux -k \
  //tensorflow/python/ops/numpy_ops:np_math_ops_test \
  --test_filter='*CloseNonBroadcastableShapesXla*'

bazel test --config=linux -k \
  //tensorflow/python/ops/numpy_ops:np_math_ops_test

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Jul 16, 2026
@furk4neg3
furk4neg3 requested a review from dmiltr3 July 16, 2026 11:41
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 16, 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.

Here is a summary of the progress and any issues we found:

  • Status: Internal tests have completed successfully with all 2514 targets passing. Open-source validation has also succeeded.

  • Action Required: You added a new import from tensorflow.python.eager import def_function in np_math_ops_test.py. Please update the dependencies for the test target in your build file (e.g., BUILD or BUILD.bazel) to explicitly include this dependency.

@furk4neg3
furk4neg3 force-pushed the fix-numpy-allclose-xla-shape branch from 28d4ca1 to 6e13bdb Compare July 16, 2026 23:43
@furk4neg3

Copy link
Copy Markdown
Contributor Author

Thanks. I added //tensorflow/python/eager:def_function to the dependencies of the np_math_ops_test target in tensorflow/python/ops/numpy_ops/BUILD.

I also fixed the PyLint indentation issue and rebased the branch onto the current master. Could you please take another look?

@furk4neg3
furk4neg3 requested a review from dmiltr3 July 16, 2026 23:48

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

Upon review, we noticed that the implementation in np_math_ops.py (specifically in isclose for integer types) used a == b. This can cause inconsistent behavior between eager execution and XLA compilation when dealing with non-broadcastable static shapes.

In TensorFlow, using == on Tensors with non-broadcastable shapes might fallback to scalar False or behave differently than expected NumPy semantics, which require raising a ValueError (Incompatible shapes). This discrepancy leads to errors during XLA compilation.

Suggested Fix

Please replace a == b with math_ops.equal(a, b) in the else branch of isclose function in third_party/tensorflow/python/ops/numpy_ops/np_math_ops.py.

    else:
      return math_ops.equal(a, b)

This ensures strict broadcasting validation matching NumPy semantics and prevents XLA compilation failures.

Tests

We also suggest adding a regression test to verify this behavior, ensuring that isclose and allclose raise appropriate errors for non-broadcastable shapes, both with and without jit_compile=True.

@furk4neg3

Copy link
Copy Markdown
Contributor Author

Thanks for the review. This change is already implemented in the latest commit (6e13bdb).

The non-inexact branch of isclose now uses:

return math_ops.equal(a, b)

The regression test also verifies that isclose and allclose raise a broadcasting-related exception for non-broadcastable integer and floating-point inputs, in both eager and jit_compile=True execution.

The required //tensorflow/python/eager:def_function BUILD dependency has also been added, and the current CI, PyLint, and License Check runs are passing.

Could you please take another look at the latest revision?

@furk4neg3
furk4neg3 requested a review from dmiltr3 July 17, 2026 01:41
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Jul 17, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Jul 17, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Jul 17, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Jul 20, 2026
@nithyak0204

Copy link
Copy Markdown

Hi @furk4neg3, Closing this PR as the proposed changes have already been merged into the codebase. Thank you for your contribution!

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Closed/Rejected in PR Queue Jul 22, 2026
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Jul 22, 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 size:M CL Change Size: Medium

Projects

Status: Closed/Rejected

Development

Successfully merging this pull request may close these issues.

tf2xla: Incompatible shapes: [4] vs. [8] under jit_compile=True (eager succeeds)

5 participants