Repository navigation
Apply rtol and atol to integer inputs in tf.experimental.numpy.isclose - #123867
Conversation
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
There was a problem hiding this comment.
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.
dmiltr3
left a comment
There was a problem hiding this comment.
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_overflow2. 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))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.
|
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 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 Verified locally: both new tests pass, and the full |
dmiltr3
left a comment
There was a problem hiding this comment.
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 <= rhsTest 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.
|
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 Re-verified locally after the rename: both promotion matrices pass and the full |
Summary
Fixes #108657.
tf.experimental.numpy.isclosecompared integer inputs with pure equality, ignoringrtolandatolentirely. The issue's repro (int32 inputs,rtol=9) returned allFalsewhere NumPy returns allTrue.allclosewas 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:
max(a, b) - min(a, b)rather thanabs(a - b), because unsigned subtraction wraps around (uint81 - 2is255) andtf.absdoes not support unsigned dtypes at all.LessEqualdo 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_nanregression cases, and integer-input/float-tolerance cases in three promotion configurations (disabled: raises as intended; legacy mode andallmode: matches NumPy). The fullnp_math_ops_test.pysuite 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.