Skip to content

Support half and bfloat16 images in resize gradients - #129738

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/129737-resize-grad-half-dtypes
Nov 2, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/129737-resize-grad-half-dtypes

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

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 through ScaleAndTranslate. The forward op takes half, bfloat16 and double images, but ScaleAndTranslateGrad is T: {float} for both grads and original_image, so backprop raises InvalidArgumentError for every dtype except float32.
  • method="bicubic" returns a None gradient for half and bfloat16 images with no error, because ResizeBicubicGrad only 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 in image_grad.py: pass the image as float32 where the kernel needs it and cast the result back to the image's dtype, which is what ResizeBilinearGrad already returns. For float32 (and float64 for bicubic) the casts are no-ops, so the existing paths don't change. Integer images still get None, 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 ScaleAndTranslateGrad error, the second because the gradient is None) and pass with the patched image_grad.py dropped into that install. The whole image_grad_test.py passes with the patch (78 tests), and so do the resize test classes in image_ops_test.py. I also checked the float64 bicubic and lanczos3 gradients against numeric Jacobians, tf.function, graph-mode tf.gradients for half, and that uint8 still returns None. pylint with tensorflow/tools/ci_build/pylintrc is clean on the changed lines. CPU only (arm64 macOS).

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
@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 06:03
@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 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.

Comment on lines +169 to +181
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)

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.

medium

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
  1. Enforce standard Python formatting conventions and ensure code readability and consistency with repository standards. (link)

@keerthanakadiri keerthanakadiri self-assigned this Oct 30, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Oct 30, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 30, 2026
@keerthanakadiri keerthanakadiri added the comp:ops OPs related issues label Oct 30, 2026
@keerthanakadiri
keerthanakadiri requested a review from a team October 30, 2026 07:43

@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 adding half, bfloat16, and float64 gradient support for ResizeBicubic and ScaleAndTranslate. Please make these three updates before we merge:

  1. Guard _ScaleAndTranslateGrad with if image.dtype.is_floating: in tensorflow/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]
  1. Add an integer-image gradient test in ScaleAndTranslateOpTestBase in tensorflow/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)
  1. 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.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 30, 2026
`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.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated in 1741b95: _ScaleAndTranslateGrad now only computes the image gradient when image.dtype.is_floating and returns None otherwise. Added testGradOnUnsupportedType (uint8 image with scale watched; it fails without the guard in both modes), and testGradForHalfAndBfloat16 / testGradsForNonFloat32Images now run in graph and eager mode.

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

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:

  1. Guard _ResizeBilinearGrad with if image.dtype.is_floating: in tensorflow/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]
  1. Cast image to dtypes.float32 in _ScaleAndTranslateGrad in tensorflow/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.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated in d08246e: _ResizeBilinearGrad now only calls resize_bilinear_grad when image.dtype.is_floating and returns None for the image otherwise, and _ScaleAndTranslateGrad casts the image to dtypes.float32 explicitly. I didn't add a bilinear test for integer images: a tape already returns None for an integer input, so such a test passes without the guard.

@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 8c13e73 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

4 participants