Repository navigation
Fix saturate_cast for int64, uint32 and uint64 inputs - #129839
copybara-service[bot] merged 4 commits into
Conversation
saturate_cast computes its upper clamp limit as `np_dtype(np.minimum(float(in_dtype.max), float(out_dtype.max)))`. float(2**63 - 1) rounds up to 2**63, which int64 cannot hold, and converting that back is platform dependent. ARM saturates to the int64 maximum, but x86 yields INT64_MIN, so for int64 input with a float, int64 or uint64 output dtype every value is clamped to INT64_MIN. Compute the limits for integer inputs with Python integers, which compare and convert exactly. uint32 and uint64 inputs also failed on every platform with NotFoundError, because ClipByValue has no kernels for them. That broke tf.image.convert_image_dtype(..., saturate=True) for those dtypes too. Clamp them with Minimum and Maximum instead. No test passed integer inputs to saturate_cast. Add one covering all integer input and output dtypes, and float outputs.
There was a problem hiding this comment.
Code Review
This pull request updates the tf.dtypes.saturate_cast implementation to correctly handle integer inputs, specifically resolving issues with int64 upper limits and uint32/uint64 input types. The changes include a new test suite, testSaturateIntegerInputs, to ensure correct numerical behavior across various integer and float types, as well as an update to the release notes. I have no feedback to provide.
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for fixing tf.dtypes.saturate_cast for int64, uint32, and uint64 inputs and adding integer test coverage. Please fix one issue with bfloat16 outputs before we merge:
-
Avoid
int(out_real_dtype.min)andint(out_real_dtype.max)overflow ontf.bfloat16(tensorflow/python/ops/math_ops.py:1196-1197):
Fortf.bfloat16,out_real_dtype.minandout_real_dtype.maxareml_dtypes.bfloat16scalars (±3.3895314e+38). Callingint()directly onml_dtypescustom floats casts through a Clongand overflows onbfloat16limits. On x86_64 Linux this returnsINT64_MIN, which raisesOverflowErrorfor narrower integer inputs and clamps allint64inputs toINT64_MIN. Convert non-integer output bounds throughfloatbefore callingint:if in_dtype.is_integer: # Compare as Python integers, which are exact. For floating-point # output dtypes, convert via float first because ml_dtypes custom # floats (e.g. bfloat16) cast through C long in __int__ and overflow. out_min = ( int(out_real_dtype.min) if out_real_dtype.is_integer else int(float(out_real_dtype.min)) ) out_max = ( int(out_real_dtype.max) if out_real_dtype.is_integer else int(float(out_real_dtype.max)) ) min_limit = np_dtype(max(int(in_dtype.min), out_min)) max_limit = np_dtype(min(int(in_dtype.max), out_max))
-
Add
dtypes.bfloat16totestSaturateIntegerInputs(tensorflow/python/kernel_tests/array_ops/cast_op_test.py:251):
Includedtypes.bfloat16in the float output loop so the test covers integer-to-bfloat16saturating casts:for out_type in [dtypes.float32, dtypes.float64, dtypes.bfloat16]: y = self.evaluate(math_ops.saturate_cast(x, dtype=out_type)) self.assertAllEqual(self.evaluate(math_ops.cast(x, out_type)), y)
…ide-int # Conflicts: # RELEASE.md
…ide-int # Conflicts: # RELEASE.md
int() on a bfloat16 scalar converts through a C long, so the output limits overflow: x86 yields INT64_MIN and arm64 INT64_MAX. Convert float output limits through float first, and cover bfloat16 in the test. The new test also fails on Windows CI for int64 to uint32. Windows CI builds without AVX, and the pinned Eigen's SSE2 pcmp_lt for Packet2l compares the low 32 bits as signed, so pmin and pmax are wrong for a limit of 2**32 - 1. saturate_cast computes the right limits; the bug is in Eigen and master gives the same result. Release builds use AVX and are not affected. Skip that one pair on Windows.
|
@dmiltr3 Both The same push also skips one test case on Windows, so please check you're happy with that. This looks like an Eigen bug, not a problem in the
So I skip only that pair on Windows, with a comment. It can come out once the Eigen bump relands. If you'd rather handle it differently, tell me. Not verified: I reproduced this with Eigen alone, not with TF built for Windows or x86. The Windows job on this push will show whether the other cases pass, since the failed run stopped at this pair. 🤖 Addressed by Claude Code |
|
🤖 Addressed by Claude Code |
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for updating the bfloat16 limit conversion, adding bfloat16 test coverage, and scoping the Windows SSE2 int64 to uint32 skip cleanly. Everything looks good to merge.
3a832ad
into
tensorflow:master
Fixes #129838
Problem
tf.dtypes.saturate_castmishandles wide integer inputs:np_dtype(np.minimum(float(in_dtype.max), float(out_dtype.max))).float(2**63 - 1)rounds up to2**63, and converting that to int64 is out of range. ARM saturates toINT64_MAX, but x86 givesINT64_MIN, so with a float32, float64, int64 or uint64 output dtype every value is clamped toINT64_MINwith no error.ClipByValuehas no kernels for them, so the call raisesNotFoundError. This also breakstf.image.convert_image_dtype(..., saturate=True)for those dtypes.Change
nextafternudge they don't need. Float inputs keep the existing path unchanged.MinimumandMaximum, which do have kernels, instead ofClipByValue. Other dtypes still useClipByValue. I kept this insaturate_castrather than adding kernels so the fix stays in Python; addingClipByValuekernels would be a reasonable alternative if you prefer it.testSaturateIntegerInputs, covering all 8 integer input dtypes against all 8 integer outputs, plus float16, float32 and float64 outputs. No existing test passed integer inputs.Testing
I don't have an x86 Linux machine or a Bazel build, so the int64 case hasn't been run on a real x86 TensorFlow build. The x86 wheel can't run under Rosetta here because it needs AVX. CI on this PR will be the first real x86 run of the new test.
On tf-nightly 2.23.0.dev20261028 (macOS arm64), with this PR's files copied in:
cast_op_test.py: 22 tests, OK (3 skipped). With the oldmath_ops.py,testSaturateIntegerInputserrors on the uint32 crash. On ARM the old code gets the int64 limit right, so this run doesn't exercise the x86 failure.convert_image_dtype(..., saturate=True)from uint32 and uint64,jit_compile=True, andRaggedTensorinput: correct output.pylint --rcfile=tensorflow/tools/ci_build/pylintrconcast_op_test.py: 10/10.Under Rosetta, using x86_64 Python and NumPy 1.26.4 with the real
saturate_castsource and only the TF ops stubbed (ClipByValueas min/max,castasastype), for[0, 5, -7, 2**40]:[-9.22e18]x4[0, 5, -7, 1.0995e12][-9.22e18]x4[0, 5, -7, 1.0995e12][-9223372036854775808]x4[0, 5, -7, 1099511627776][9223372036854775808]x4[0, 5, 0, 1099511627776]The arm64 run of the same script gives the "this PR" column for both versions.
Notes
If someone can run the snippet from the issue on x86 Linux, that would confirm the int64 report directly. I added a
RELEASE.mdentry because outputs change for those inputs.