Repository navigation
Support half and bfloat16 images in resize gradients - #129738
copybara-service[bot] merged 3 commits into
Conversation
ScaleAndTranslateGrad only has a float32 kernel, and its original_image input shares T with grads, while the forward ScaleAndTranslate op takes half, bfloat16 and double images. Backprop through tf.image.resize with antialias=True or the lanczos/gaussian/mitchellcubic kernels therefore fails for every dtype except float32. The kernel only reads the shape of original_image, so pass it as float32 and cast the gradient back to the image's dtype. The bicubic gradient had the same gap but failed silently: it returned None for half and bfloat16 images because ResizeBicubicGrad has no 16-bit kernel. Compute it in float32 for those and cast back, the same way. Fixes tensorflow#129737
There was a problem hiding this comment.
Code Review
This pull request enables gradient computations for non-float32 images (such as float16, bfloat16, and float64) in ScaleAndTranslateGrad and ResizeBicubicGrad by casting inputs to supported types during computation and casting the output gradients back to the original image's dtype. It also adds comprehensive unit tests to verify these changes. The feedback suggests improving code readability in _ResizeBicubicGrad by using a separate variable for the casted image instead of reassigning the original image variable.
| image = op.inputs[0] | ||
| grad0 = None | ||
| if op.inputs[0].dtype in allowed_types: | ||
| if image.dtype.is_floating: | ||
| # ResizeBicubicGrad only takes float32 and float64 images, so compute the | ||
| # gradient for half and bfloat16 images in float32. | ||
| if image.dtype not in allowed_types: | ||
| image = math_ops.cast(image, dtypes.float32) | ||
| grad0 = gen_image_ops.resize_bicubic_grad( | ||
| grad, | ||
| op.inputs[0], | ||
| image, | ||
| align_corners=op.get_attr("align_corners"), | ||
| half_pixel_centers=op.get_attr("half_pixel_centers")) | ||
| grad0 = math_ops.cast(grad0, op.inputs[0].dtype) |
There was a problem hiding this comment.
Reassigning the image variable to its casted version (dtypes.float32) makes the subsequent use of op.inputs[0].dtype necessary but confusing, as image.dtype no longer refers to the original image's dtype. It is cleaner and less error-prone to keep image unmodified and use a separate variable (e.g., grad_image) for the casted tensor. This allows using image.dtype consistently throughout the function.
image = op.inputs[0]\n grad0 = None\n if image.dtype.is_floating:\n # ResizeBicubicGrad only takes float32 and float64 images, so compute the\n # gradient for half and bfloat16 images in float32.\n grad_image = image\n if image.dtype not in allowed_types:\n grad_image = math_ops.cast(image, dtypes.float32)\n grad0 = gen_image_ops.resize_bicubic_grad(\n grad,\n grad_image,\n align_corners=op.get_attr(\"align_corners\"),\n half_pixel_centers=op.get_attr(\"half_pixel_centers\"))\n grad0 = math_ops.cast(grad0, image.dtype)References
- Enforce standard Python formatting conventions and ensure code readability and consistency with repository standards. (link)
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for adding half, bfloat16, and float64 gradient support for ResizeBicubic and ScaleAndTranslate. Please make these three updates before we merge:
- Guard
_ScaleAndTranslateGradwithif image.dtype.is_floating:intensorflow/python/ops/image_grad.py(lines 143-154)
ScaleAndTranslate accepts integer images alongside float32 tensors for scale and translation. If a caller watches scale or translation, TensorFlow still invokes _ScaleAndTranslateGrad. Please guard the gradient calculation with if image.dtype.is_floating: so integer images return None instead of casting gradients to integer types:
image = op.inputs[0]
grad0 = None
if image.dtype.is_floating:
# ScaleAndTranslateGrad only has a float32 kernel and only reads the shape
# of the original image, while the forward op also accepts half, bfloat16
# and double images. Run it in float32 and return the input's dtype.
grad0 = gen_image_ops.scale_and_translate_grad(
grad,
math_ops.cast(image, grad.dtype),
op.inputs[2],
op.inputs[3],
kernel_type=op.get_attr("kernel_type"),
antialias=op.get_attr("antialias"))
grad0 = math_ops.cast(grad0, image.dtype)
return [grad0, None, None, None]- Add an integer-image gradient test in
ScaleAndTranslateOpTestBaseintensorflow/python/ops/image_grad_test_base.py(line 730)
Please add a unit test verifying that a uint8 image receives a None gradient when scale is watched:
@test_util.run_in_graph_and_eager_modes
def testGradOnUnsupportedType(self):
in_shape = [1, 2, 3, 1]
out_shape = [1, 4, 6, 1]
x = np.arange(0, 6).reshape(in_shape).astype(np.uint8)
input_tensor = constant_op.constant(x, shape=in_shape)
scale = constant_op.constant((0.37, 2.1))
translation = constant_op.constant((1.19, 0.0))
with backprop.GradientTape() as tape:
tape.watch(input_tensor)
tape.watch(scale)
out = image_ops.scale_and_translate(
input_tensor, out_shape[1:3], scale=scale, translation=translation)
grad_image, grad_scale = tape.gradient(out, [input_tensor, scale])
self.assertIsNone(grad_image)
self.assertIsNone(grad_scale)- Run the new gradient tests in both graph and eager modes in
tensorflow/python/ops/image_grad_test_base.py(lines 627 and 696)
Neither ResizeBicubicOpTestBase nor ScaleAndTranslateOpTestBase has a class-level mode decorator. Please decorate testGradForHalfAndBfloat16 and testGradsForNonFloat32Images with @test_util.run_in_graph_and_eager_modes so both tests cover graph and eager execution.
`ScaleAndTranslate` also accepts integer images, and the gradient function is still invoked when only `scale` or `translation` is watched. Cast the gradient back to the image dtype only for floating images and return `None` for the image otherwise, instead of casting the gradient to an integer type. Add a uint8 test for this, and run `testGradForHalfAndBfloat16` and `testGradsForNonFloat32Images` in both graph and eager mode.
|
Updated in 1741b95: |
dmiltr3
left a comment
There was a problem hiding this comment.
All three requests from our previous review (_ScaleAndTranslateGrad floating-point guard, testGradOnUnsupportedType in ScaleAndTranslateOpTestBase, and @test_util.run_in_graph_and_eager_modes on the new gradient tests) are resolved in commit 1741b954.
Please make two remaining updates in tensorflow/python/ops/image_grad.py:
- Guard
_ResizeBilinearGradwithif image.dtype.is_floating:intensorflow/python/ops/image_grad.py(lines 120-125)
ResizeBilinear accepts integer images, while ResizeBilinearGrad only accepts floating-point types. Please guard gen_image_ops.resize_bilinear_grad with if image.dtype.is_floating: so integer images return None gradients, matching _ScaleAndTranslateGrad and _ResizeBicubicGrad:
image = op.inputs[0]
grad0 = None
if image.dtype.is_floating:
grad0 = gen_image_ops.resize_bilinear_grad(
grad,
image,
align_corners=op.get_attr("align_corners"),
half_pixel_centers=op.get_attr("half_pixel_centers"))
return [grad0, None]- Cast
imagetodtypes.float32in_ScaleAndTranslateGradintensorflow/python/ops/image_grad.py(line 151)
Please pass dtypes.float32 instead of grad.dtype in math_ops.cast(image, dtypes.float32) so the target type required by the kernel is explicit and matches _ResizeBicubicGrad at line 178:
math_ops.cast(image, dtypes.float32),`ResizeBilinear` accepts integer images, but `ResizeBilinearGrad` only takes floating-point types. Compute the image gradient only for floating images and return `None` otherwise, as `_ResizeBicubicGrad` and `_ScaleAndTranslateGrad` do. Also cast the image to `dtypes.float32` explicitly in `_ScaleAndTranslateGrad`, the type its kernel requires, rather than relying on the dtype of the incoming gradient.
|
Updated in d08246e: |
Fixes #129737.
Two resize gradients don't handle half/bfloat16 images, which breaks mixed precision training for models that resize inside the graph:
tf.image.resize(..., antialias=True)and the lanczos/gaussian/mitchellcubic methods go throughScaleAndTranslate. The forward op takes half, bfloat16 and double images, butScaleAndTranslateGradisT: {float}for bothgradsandoriginal_image, so backprop raisesInvalidArgumentErrorfor every dtype except float32.method="bicubic"returns aNonegradient for half and bfloat16 images with no error, becauseResizeBicubicGradonly has float/double kernels and the Python gradient skips other dtypes.Both grad kernels only read the shape of
original_image, so the fix stays inimage_grad.py: pass the image as float32 where the kernel needs it and cast the result back to the image's dtype, which is whatResizeBilinearGradalready returns. For float32 (and float64 for bicubic) the casts are no-ops, so the existing paths don't change. Integer images still getNone, as before.I went with the Python-side cast instead of adding 16-bit kernels for the two grad ops since it's a much smaller change and the gradient is computed in float32 either way (the forward op's output is float32).
Testing
ScaleAndTranslateOpTestBase.testGradsForNonFloat32Images: half, bfloat16 and float64 gradients for lanczos3/gaussian/mitchellcubic, with and without antialias, have the input's dtype and match the float32 gradient.ResizeBicubicOpTestBase.testGradForHalfAndBfloat16: same check for bicubic.Both fail on tf-nightly 2.23.0-dev20261028 (the first with the
ScaleAndTranslateGraderror, the second because the gradient isNone) and pass with the patchedimage_grad.pydropped into that install. The wholeimage_grad_test.pypasses with the patch (78 tests), and so do the resize test classes inimage_ops_test.py. I also checked the float64 bicubic and lanczos3 gradients against numeric Jacobians,tf.function, graph-modetf.gradientsfor half, and that uint8 still returnsNone. pylint withtensorflow/tools/ci_build/pylintrcis clean on the changed lines. CPU only (arm64 macOS).