Skip to content

Fix saturate_cast for int64, uint32 and uint64 inputs - #129839

Merged
copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/saturate-cast-wide-int
Nov 9, 2026
Merged

copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/saturate-cast-wide-int

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

Fixes #129838

Problem

tf.dtypes.saturate_cast mishandles wide integer inputs:

  • int64 input on x86: the upper clamp limit is computed as np_dtype(np.minimum(float(in_dtype.max), float(out_dtype.max))). float(2**63 - 1) rounds up to 2**63, and converting that to int64 is out of range. ARM saturates to INT64_MAX, but x86 gives INT64_MIN, so with a float32, float64, int64 or uint64 output dtype every value is clamped to INT64_MIN with no error.
  • uint32 and uint64 input on every platform: ClipByValue has no kernels for them, so the call raises NotFoundError. This also breaks tf.image.convert_image_dtype(..., saturate=True) for those dtypes.

Change

  • For integer inputs, compute both limits with Python integers, which compare and convert exactly, and skip the nextafter nudge they don't need. Float inputs keep the existing path unchanged.
  • For uint32 and uint64, clamp with Minimum and Maximum, which do have kernels, instead of ClipByValue. Other dtypes still use ClipByValue. I kept this in saturate_cast rather than adding kernels so the fix stays in Python; adding ClipByValue kernels would be a reasonable alternative if you prefer it.
  • Add 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 old math_ops.py, testSaturateIntegerInputs errors 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, and RaggedTensor input: correct output.
  • pylint --rcfile=tensorflow/tools/ci_build/pylintrc on cast_op_test.py: 10/10.

Under Rosetta, using x86_64 Python and NumPy 1.26.4 with the real saturate_cast source and only the TF ops stubbed (ClipByValue as min/max, cast as astype), for [0, 5, -7, 2**40]:

Cast master this PR
int64 -> float32 [-9.22e18] x4 [0, 5, -7, 1.0995e12]
int64 -> float64 [-9.22e18] x4 [0, 5, -7, 1.0995e12]
int64 -> int64 [-9223372036854775808] x4 [0, 5, -7, 1099511627776]
int64 -> uint64 [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.md entry because outputs change for those inputs.

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.
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Nov 2, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios November 2, 2026 14:30
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Nov 2, 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 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.

@nithyak0204 nithyak0204 self-assigned this Nov 3, 2026
@nithyak0204
nithyak0204 requested a review from a team November 3, 2026 04:30
@nithyak0204 nithyak0204 added python Pull requests that update Python code prtype:bugfix PR to fix a bug labels Nov 3, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Nov 3, 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.

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:

  1. Avoid int(out_real_dtype.min) and int(out_real_dtype.max) overflow on tf.bfloat16 (tensorflow/python/ops/math_ops.py:1196-1197):
    For tf.bfloat16, out_real_dtype.min and out_real_dtype.max are ml_dtypes.bfloat16 scalars (±3.3895314e+38). Calling int() directly on ml_dtypes custom floats casts through a C long and overflows on bfloat16 limits. On x86_64 Linux this returns INT64_MIN, which raises OverflowError for narrower integer inputs and clamps all int64 inputs to INT64_MIN. Convert non-integer output bounds through float before calling int:

        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))
  2. Add dtypes.bfloat16 to testSaturateIntegerInputs (tensorflow/python/kernel_tests/array_ops/cast_op_test.py:251):
    Include dtypes.bfloat16 in the float output loop so the test covers integer-to-bfloat16 saturating 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)

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Nov 3, 2026
@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Nov 4, 2026
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.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Both bfloat16 items are done in 8cd3d8e. Float output limits now go through float first, and bfloat16 is in the test's float loop. Under Rosetta, int() on the bfloat16 max gives INT64_MIN, as you described; arm64 gives INT64_MAX.

The same push also skips one test case on Windows, so please check you're happy with that. build-windows-x86 failed the new test for int64 to uint32:

expected [0, 0, 0, 1, 5, 4294967295, 4294967295]
got      [0, 0, 0, 0, 0, 0, 4294967295]

This looks like an Eigen bug, not a problem in the saturate_cast limits:

  • Cause: the SSE2 pcmp_lt<Packet2l> at the pinned Eigen (ea13a98decd4) compares the low 32 bits as signed, so pmin and pmax go wrong for a limit of 2^32 - 1. The last element is right because it takes the scalar path.
  • Why only Windows: windows_x86_cpu_2022 doesn't enable AVX, while rbe_linux and release_cpu_windows do, and AVX builds use _mm_cmpgt_epi64.
  • Reproduction: a standalone x86-64 program that mirrors UnaryClipFunc and then casts gives that exact output at the pinned Eigen on SSE2, and it's the only wrong pair of the 64 integer pairs. It's correct with -msse4.2, and correct on SSE2 with the Eigen headers from the 2026-10-28 nightly. 1da510b8155f has the fix, but 4191b8b reverted that bump on Nov 2.

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

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Nov 4, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

build-linux-x86-cuda13 failed on 8cd3d8e, but this looks unrelated to the PR. All 816 tests passed, including cast_op_test_gpu. The job failed in the loading phase because pip fetches for nvidia-nvvm==13.4.59 and nvidia-cufft==12.4.0.34 hit the 600s timeout (Timed out). This PR doesn't touch dependencies. Could a maintainer re-run that job when convenient?

build-windows-x86 passes on this head with the int64 to uint32 pair skipped.

🤖 Addressed by Claude Code

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

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.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Nov 5, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Nov 5, 2026
@copybara-service
copybara-service Bot merged commit 3a832ad into tensorflow:master Nov 9, 2026
18 of 19 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kokoro:force-run Tests on submitted change prtype:bugfix PR to fix a bug python Pull requests that update Python code 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.dtypes.saturate_cast: int64 input clamps to INT64_MIN on x86; uint32/uint64 input raises NotFoundError

3 participants