Repository navigation
Avoid overflow in convert_image_dtype with half and wide int types - #129732
Conversation
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
There was a problem hiding this comment.
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.
dmiltr3
left a comment
There was a problem hiding this comment.
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
uint64anduint32coverage in the new wide-integer tests (tensorflow/python/ops/image_ops_test.py:5386-5397):uint64is the upper boundary wheredtype.max + 1reaches2**64and relies onnp_dtypebeing a float type. Bothfloat32/float64touint64anduint32/uint64tofloat16use the new branches. Please addfloat32 -> uint64andfloat64 -> uint64totestConvertFloatToWideIntegerStaysInRangeand includedtypes.uint32anddtypes.uint64intestConvertWideIntegerToHalf:
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.])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.
|
Updated in acbb8de: |
dmiltr3
left a comment
There was a problem hiding this comment.
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
int32doctest output inadjust_hue(tensorflow/python/ops/image_ops_impl.py:2837-2844):adjust_hueconverts integer inputs tofloat32and back viaconvert_image_dtype. Becausefloat32toint32now scales by2147483520.0instead of2**31, the unchanged channels in theint32example truncate one value lower. Please update the expected doctest output intensorflow/python/ops/image_ops_impl.py:2837-2844to 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.
|
Updated in 954b1cc: changed the |
Fixes #129731.
For float -> int,
convert_image_dtypemultiplies bydtype.max + 0.5in the image's own float type. When that type can't represent the constant it rounds up todtype.max + 1or more, and 1.0 then scales to one past the integer range: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.5exactly for 8 and 16 bit targets), and the scale is capped at the largest value belowdtype.max + 1in 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 nudgingsaturate_castalready 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
ConvertImageTestcovering half/bfloat16 -> uint8/int16/uint16, float -> int32/uint32/int64 (including -1.0 andsaturate=True), and uint16/int32/int64 -> half. All three fail on tf-nightly 2.23.0-dev20261028 and pass with the patchedimage_ops_impl.pydropped into that install. I also ran the wholeimage_ops_test.pyboth 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 withtensorflow/tools/ci_build/pylintrcis clean on the changed lines. I only tested on CPU (arm64 macOS); the change is Python-level dtype logic with no new ops.