Skip to content

Apply rtol and atol to integer inputs in tf.experimental.numpy.isclose - #123867

Merged
copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
vishwakt:fix-tnp-isclose-integer
Jul 28, 2026
Merged

copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
vishwakt:fix-tnp-isclose-integer

Conversation

@vishwakt

Copy link
Copy Markdown
Contributor

Summary

Fixes #108657.

tf.experimental.numpy.isclose compared integer inputs with pure equality, ignoring rtol and atol entirely. The issue's repro (int32 inputs, rtol=9) returned all False where NumPy returns all True. allclose was affected through the same path.

Approach

This implements the approach maintainers agreed on in #108702 (comment by @ratgr following internal discussion): apply the tolerance formula to integer inputs using the operands' own arithmetic, with no unconditional cast to floating point. Integer tolerances stay in integer arithmetic; floating-point tolerances (including the defaults) require type promotion, which keeps the cost of promotion opt-in. Both prior PRs for this issue (#108702, #109328) were closed by the stale bot, not rejected.

Two details surfaced during verification:

  • The difference is computed as max(a, b) - min(a, b) rather than abs(a - b), because unsigned subtraction wraps around (uint8 1 - 2 is 255) and tf.abs does not support unsigned dtypes at all.
  • When promotion turns the tolerance side into floating point, the integer difference is cast to match it, because comparison ops like LessEqual do not promote mixed operands. This cast is only reachable on the promotion-enabled float-tolerance path.

Verification

Verified locally against NumPy (not just by CI): int32/int64 broadcast cases including the issue's repro, uint8 wraparound cases, float-path and equal_nan regression cases, and integer-input/float-tolerance cases in three promotion configurations (disabled: raises as intended; legacy mode and all mode: matches NumPy). The full np_math_ops_test.py suite passes (48 tests).

Release notes updated as requested by maintainers in the prior PR discussion.

Credit to @Thrsu for the report, and to @gamila-wisam and @ayushozha for the earlier attempts.

isclose compared integer inputs with pure equality, ignoring the
tolerances entirely, so inputs well within rtol or atol of each other
reported False where NumPy reports True.

Apply the tolerance formula to integer inputs using the operands' own
arithmetic, following the implementation agreed on by maintainers in
PR tensorflow#108702: no unconditional cast to floating point, so integer
tolerances stay in integer arithmetic and floating-point tolerances
require type promotion, keeping the cost of promotion opt-in. The
difference is computed as max - min because unsigned subtraction wraps
around and tf.abs does not support unsigned dtypes. When promotion
yields a floating-point tolerance side, the difference is cast to match
it, since comparison ops do not promote mixed operands.

Verified against NumPy across int32, int64, and uint8 inputs with
integer and float tolerances, with type promotion disabled, in legacy
mode, and in all mode. Also updates release notes as requested by
maintainers.

Fixes tensorflow#108657
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Jul 23, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios July 23, 2026 19:13
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 23, 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 updates tf.experimental.numpy.isclose and tf.experimental.numpy.allclose to correctly apply rtol and atol tolerances to integer inputs using integer arithmetic, and adds corresponding unit tests. The review feedback highlights a critical issue where signed integer subtraction can overflow when the absolute difference exceeds the maximum representable value of the type, leading to incorrect True results. A code suggestion is provided to handle this overflow by verifying that the difference remains non-negative for signed integers.

max - min overflows for signed integers when the true difference
exceeds the dtype maximum (for example int8 127 - (-128)). Two's
complement overflow always produces a negative value, and since
tolerances are non-negative, the wrapped difference would incorrectly
compare as close. A negative diff therefore proves overflow; such pairs
are now treated as not close, matching NumPy, which computes these
distances in floating point.
@nithyak0204
nithyak0204 requested a review from a team July 24, 2026 07:32
@nithyak0204 nithyak0204 added comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Jul 24, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Jul 24, 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.

Review Summary

The implementation correctly addresses the issue where integer inputs were compared using pure equality, ignoring tolerances. The approach of using max(a, b) - min(a, b) is robust for handling unsigned integer wraparound and avoiding tf.abs limitations.

Findings & Suggested Improvements

1. Identical MIN_INT Edge Case

I found an edge case involving MIN_INT (e.g., -128 for int8) when rtol > 0 (integer).
In this scenario, math_ops.abs(b) overflows and becomes negative (-128). This causes the right-hand side rhs = atol + rtol * abs_b to become negative or overflow downwards.
As a result, identical MIN_INT values (a = b = MIN_INT) can be reported as not close because diff (0) is compared against a negative rhs.

Suggestion: Add a fallback to ensure identical values are always considered close, guarding against tolerance overflow:

      # Identical values should always be close; guard against rhs overflow
      # (e.g. with MIN_INT and integer rtol).
      result = result | math_ops.equal(a, b)

This should be placed before applying no_overflow:

      result = diff <= rhs
      result = result | math_ops.equal(a, b)
      if no_overflow is not None:
        result = result & no_overflow

2. Close but not Identical MIN_INT Divergence

For values close to MIN_INT but not identical (e.g., a = -127, b = -128 in int8), the same rhs overflow occurs. In integer arithmetic without promotion, this leads to reporting them as not close, whereas NumPy (which promotes to float) reports them as close.
You acknowledged this in comments ("abs(b) can also overflow for the most negative value, which conservatively shrinks rtol-scaled tolerances"). It might be worth explicitly stating that this can flip the sign of the tolerance making it impossible to satisfy, effectively reporting "not close" even if they are close in math.

Tests

Here are some test cases that cover these scenarios:

  def testIsCloseMinIntEdgeCase(self):
    # Identical MIN_INT values with integer rtol should be close.
    a = np.array([-128], np.int8)
    b = np.array([-128], np.int8)
    self.match(
        np_math_ops.isclose(a, b, rtol=5, atol=0),
        np.isclose(a, b, rtol=5, atol=0))

  def testIsCloseMinIntEdgeCaseClose(self):
    # This test may diverge from NumPy if we accept integer arithmetic limitations (tolerance overflow).
    a = np.array([-127], np.int8)
    b = np.array([-128], np.int8)
    # NumPy reports True (promotes to float).
    # Our integer path might report False due to rhs overflow.
    self.match(
        np_math_ops.isclose(a, b, rtol=5, atol=0),
        np.isclose(a, b, rtol=5, atol=0))

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Jul 27, 2026
For the most negative value of a signed dtype, abs(b) overflows and
wraps the rtol-scaled tolerance negative, which made identical values
(a = b = MIN_INT with integer rtol > 0) report as not close. Identical
values must always be close, so add an explicit equality fallback.

For values near MIN_INT that are close but not identical, the wrapped
tolerance remains impossible to satisfy in integer arithmetic; that
divergence from NumPy is retained as a documented limitation of the
no-casting design (type promotion with float tolerances gives NumPy
results) and is now covered by an explicit test and sharper comment
wording.
@vishwakt

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review @dmiltr3, finding 1 was a genuine bug. Both findings are addressed in 8ca3e99:

Finding 1 (identical MIN_INT values): Fixed with the equality fallback you suggested, placed before the overflow mask. Identical values now always report close. Your test case is included as testIsCloseMinIntIdenticalValues.

Finding 2 (close but not identical near MIN_INT): Kept as a documented limitation rather than fixed, since the true tolerance (e.g. 640 for int8 rtol=5) is not representable in the input dtype and fixing it would require the float casting this implementation deliberately avoids per the maintainer guidance in #108702. Two changes to make that explicit: the code comment now states that the wrapped tolerance flips sign and becomes impossible to satisfy (your wording suggestion), and I adapted your second test case into testIsCloseMinIntNeighborDivergesFromNumPy, which asserts our conservative result and NumPy's differing result side by side, so the divergence is pinned by a test rather than left implicit. As written with self.match it would have failed, since we intentionally do not match NumPy there; enabling type promotion with float tolerances gives the NumPy result.

Verified locally: both new tests pass, and the full np_math_ops_test.py suite is green (51 tests).

@nithyak0204
nithyak0204 requested a review from dmiltr3 July 27, 2026 15:02

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

Please update your GitHub PR with this change to ensure the linter passes. Here is the suggested code change:

# In np_math_ops.py, inside isclose integer path:

# Change:
diff = math_ops.maximum(a, b) - math_ops.minimum(a, b)
# ...
no_overflow = diff >= 0
# ...
if rhs.dtype != diff.dtype:
  diff = math_ops.cast(diff, rhs.dtype)
result = diff <= rhs

# To:
diff_val = math_ops.maximum(a, b) - math_ops.minimum(a, b)
# ...
no_overflow = diff_val >= 0
# ...
if rhs.dtype != diff_val.dtype:
  diff_val = math_ops.cast(diff_val, rhs.dtype)
result = diff_val <= rhs

Test Status

Internal tests have passed successfully. The logic is sound, but please apply the lint fix above to ensure all checks pass.

The local shadowed the module-level diff function (tnp.diff) defined in
the same file. Harmless, since the enclosing function never calls it,
and not flagged by the configured linter, but avoiding the shadow reads
better.
@vishwakt

Copy link
Copy Markdown
Contributor Author

Applied in ce1623e, with one correction for the record: all checks on this PR were already green, including PyLint, so there was no failing linter to fix. TF's PyLint configuration does not flag this pattern.

That said, the rename is a genuine readability improvement for a reason the review did not mention: the local diff shadowed the module-level diff function (tnp.diff) defined later in the same file. The shadow was harmless since isclose never calls tnp.diff, but avoiding it is better hygiene, so I was happy to take the change on those grounds.

Re-verified locally after the rename: both promotion matrices pass and the full np_math_ops_test.py suite is green (51 tests).

@dmiltr3
dmiltr3 self-requested a review July 27, 2026 23:23
@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 27, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Jul 27, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Jul 27, 2026
@dmiltr3
dmiltr3 self-requested a review July 27, 2026 23:50
@google-ml-butler google-ml-butler Bot added the kokoro:force-run Tests on submitted change label Jul 27, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Jul 27, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Jul 28, 2026
@copybara-service
copybara-service Bot merged commit 09a3302 into tensorflow:master Jul 28, 2026
19 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Jul 28, 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:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.experimental.numpy.isclose returns incorrect results for integer inputs

5 participants