Skip to content

Avoid overflow in convert_image_dtype with half and wide int types - #129732

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/129731-convert-image-dtype-overflow
Nov 2, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/129731-convert-image-dtype-overflow

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

Fixes #129731.

For float -> int, convert_image_dtype multiplies by dtype.max + 0.5 in the image's own float type. When that type can't represent the constant it rounds up to dtype.max + 1 or more, and 1.0 then scales to one past the integer range:

c = tf.image.convert_image_dtype
c(tf.constant([0., .5, 1.], tf.bfloat16), tf.uint8)   # [0, 128, 0]          scale = 256
c(tf.constant([0., .5, 1.], tf.float16), tf.int16)    # [0, 16384, -32768]   scale = 32768
c(tf.constant([0., .5, 1.], tf.float16), tf.uint16)   # [0, 65535, 65535]    scale = inf
c(tf.constant([0, 65535], tf.uint16), tf.float16)     # [0, inf]

float32 -> int32/uint32 and float64 -> int64 have the same rounding (231, 232, 2**63), so 1.0 overflows the cast there too, which is undefined and is what #60078 ran into on Windows.

The fix only kicks in when the scale would round up. In that case half and bfloat16 images are scaled in float32 (which holds dtype.max + 0.5 exactly for 8 and 16 bit targets), and the scale is capped at the largest value below dtype.max + 1 in the compute type, so 1.0 always stays in range. For int32 and wider targets that means 1.0 maps to the largest float32/float64 below 2**31 etc., e.g. 2147483520 for int32. This is the same nudging saturate_cast already does for its clamp limits. For int -> float, when the integer max doesn't fit in the target (uint16 and wider into half), the multiply happens in float32 and only the result in [-1, 1] is cast down.

I kept the common paths untouched on purpose. Comparing old and new outputs over every half/bfloat16 value in [-1, 1], 300k float32/float64 values, and integer ranges for each dtype pair (with and without saturate), all 50 combinations that weren't overflowing (float32 -> uint8, half -> uint8, bfloat16 -> int8, int8 -> half, uint8 -> float32, ...) give bit-identical results. Only the overflowing pairs change. The output op name is unchanged in graph mode.

Testing

Added three tests to ConvertImageTest covering half/bfloat16 -> uint8/int16/uint16, float -> int32/uint32/int64 (including -1.0 and saturate=True), and uint16/int32/int64 -> half. All three fail on tf-nightly 2.23.0-dev20261028 and pass with the patched image_ops_impl.py dropped into that install. I also ran the whole image_ops_test.py both ways: the patched run has no failures beyond the unpatched baseline (the only differences are the three new tests, and the decode tests that need Bazel testdata error out in both runs). pylint with tensorflow/tools/ci_build/pylintrc is clean on the changed lines. I only tested on CPU (arm64 macOS); the change is Python-level dtype logic with no new ops.

The float -> int path multiplies by dtype.max + 0.5 in the image's own
float type. That constant rounds up to dtype.max + 1 or more when the
type can't hold it: 256 in bfloat16 for uint8, 32768 in half for int16,
inf in half for uint16, 2**31 in float32 for int32. An input of 1.0
then lands one past the integer range and the cast wraps it, so a white
bfloat16 pixel converts to uint8 0 and half 1.0 converts to int16
-32768. For float32 -> int32/uint32 the overflowing cast is undefined
and the result differs between platforms.

The int -> float path has the same problem the other way around: uint16
and wider values don't fit in half, so uint16 max becomes inf and int32
input becomes nan.

When the scale would round up, multiply in float32 for half and
bfloat16 and use the largest scale below dtype.max + 1. Integers that
don't fit in the target float type are scaled in float32 and the result
is cast afterwards. Conversions that never hit this (float32 -> uint8,
half -> uint8, int8 -> half, ...) take the same path as before and give
identical results.

Fixes tensorflow#129731
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Oct 30, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 30, 2026 05:01
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 30, 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 convert_image_dtype in image_ops_impl.py to prevent overflow and precision issues when converting between various float and integer data types. Specifically, it addresses cases where large integers overflow half-precision floats during integer-to-float conversion, and where rounding of the scaling factor causes overflow during float-to-integer conversion (particularly for 16-bit floats like float16 and bfloat16). Corresponding unit tests have been added to verify these conversions. I have no feedback to provide as the implementation is robust and includes comprehensive test coverage.

@nithyak0204 nithyak0204 self-assigned this Oct 30, 2026
@nithyak0204
nithyak0204 requested a review from a team October 30, 2026 05:33
@nithyak0204 nithyak0204 added comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Oct 30, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 30, 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 the overflow in tf.image.convert_image_dtype for narrow floats and wide integer types. The implementation in tensorflow/python/ops/image_ops_impl.py is clean and leaves non-overflowing dtype conversions unchanged.

Please make one small test update before we merge:

  • Add uint64 and uint32 coverage in the new wide-integer tests (tensorflow/python/ops/image_ops_test.py:5386-5397): uint64 is the upper boundary where dtype.max + 1 reaches 2**64 and relies on np_dtype being a float type. Both float32/float64 to uint64 and uint32/uint64 to float16 use the new branches. Please add float32 -> uint64 and float64 -> uint64 to testConvertFloatToWideIntegerStaysInRange and include dtypes.uint32 and dtypes.uint64 in testConvertWideIntegerToHalf:
    for float_dtype, int_dtype, expected in [
        (dtypes.float32, dtypes.uint32, 4294967040),
        (dtypes.float32, dtypes.uint64, 18446742974197923840),
        (dtypes.float64, dtypes.uint64, 18446744073709549568)]:
      image = constant_op.constant([0., 1.], float_dtype)
      for saturate in [False, True]:
        y = image_ops.convert_image_dtype(image, int_dtype, saturate)
        self.assertAllEqual(self.evaluate(y), [0, expected])

  def testConvertWideIntegerToHalf(self):
    # uint16 and wider integers used to overflow half in the cast, turning the
    # max value into inf (or nan once scaled).
    for int_dtype in [
        dtypes.uint16, dtypes.int32, dtypes.uint32, dtypes.int64, dtypes.uint64
    ]:
      image = constant_op.constant(
          [0, int_dtype.max // 2, int_dtype.max], int_dtype)
      y = image_ops.convert_image_dtype(image, dtypes.float16)
      self.assertAllClose(self.evaluate(y), [0., 0.5, 1.])

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 30, 2026
uint64 is the boundary where `dtype.max + 1` reaches 2**64, so test
float32 and float64 to uint64 (and float32 to uint32) with and without
saturation, and add uint32 and uint64 to the integer-to-float16 test.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated in acbb8de: testConvertFloatToWideIntegerStaysInRange now covers float32 -> uint32, float32 -> uint64 and float64 -> uint64 (with and without saturate), and testConvertWideIntegerToHalf includes uint32 and uint64.

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

The uint32 and uint64 test additions in tensorflow/python/ops/image_ops_test.py look good and resolve the previous feedback.

One docstring example needs an update for internal presubmit tests to pass:

  • Update the int32 doctest output in adjust_hue (tensorflow/python/ops/image_ops_impl.py:2837-2844): adjust_hue converts integer inputs to float32 and back via convert_image_dtype. Because float32 to int32 now scales by 2147483520.0 instead of 2**31, the unchanged channels in the int32 example truncate one value lower. Please update the expected doctest output in tensorflow/python/ops/image_ops_impl.py:2837-2844 to match:
  >>> image = [[[1, 2, 3], [4, 5, 6]],
  ...          [[7, 8, 9], [10, 11, 12]],
  ...          [[13, 14, 15], [16, 17, 18]]]
  >>> image = tf.constant(image)
  >>> tf.image.adjust_hue(image, 0.2)
  <tf.Tensor: shape=(3, 2, 3), dtype=int32, numpy=
  array([[[ 2,  0,  2],
        [ 5,  3,  5]],
       [[ 8,  6,  8],
        [11,  9, 11]],
       [[14, 12, 14],
        [17, 15, 17]]], dtype=int32)>

`adjust_hue` converts integer images to float32 and back through
`convert_image_dtype`. Float32 to int32 now scales by 2147483520.0
instead of 2**31, so the unchanged channels in the int32 example come
out one lower.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated in 954b1cc: changed the adjust_hue int32 doctest output to the values you gave. I ran the example with this branch's code and it returns exactly that array.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 30, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 30, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Oct 30, 2026
@copybara-service
copybara-service Bot merged commit a2cd6cb into tensorflow:master Nov 2, 2026
19 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Nov 2, 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 kokoro:force-run Tests on submitted change 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.image.convert_image_dtype overflows with bfloat16/half and wide ints (bfloat16 1.0 -> uint8 gives 0)

3 participants