Skip to content

Compute resize_with_pad sizes exactly instead of in float32 - #129784

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/resize-with-pad-rounding
Nov 3, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/resize-with-pad-rounding

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

Fixes #129783

Problem

tf.image.resize_with_pad computes the scale factor and the resized size in float32, then floors it. When the scaled size is a whole number, float32 often lands just below it, so the image is resized one pixel short of the target and padded with a row or column of zeros. For example, 512x512 -> 224x224 becomes a 223x223 image with a black bottom row and right column, even though the aspect ratio already matches. The padding comes from the same float, so it can also be one pixel off and shift the image. Over 200,000 random size combinations, about 5% are affected, including common ones such as 480x640 -> 300x300 and 720x1280 -> 600x600.

Change

_resize_image_with_pad_common now evaluates the same formulas in int64 arithmetic:

  • resized size: min(target, size * other_target // other_size), which equals floor(size / ratio) with ratio = max(width / target_width, height / target_height);
  • padding: max(0, (target * other_size - size * other_target) // (2 * other_size)), which equals floor((target - size / ratio) / 2).

On 200,000 random combinations of sizes from 1 to 2000, these match exact rational arithmetic everywhere. The float32 version differed in 10,099 cases. Wherever float32 was already exact, the results are unchanged. int64 is used so the products cannot overflow for any int32 size. The now-unused max_ helper is removed.

Add testNoExtraPaddingFromRounding to both ResizeImageWithPadV1Test and ResizeImageWithPadV2Test, using sizes that used to get the extra padding.

Testing

I don't have a Bazel build. I ran the changed tests with Python against the tf-nightly 2.23.0.dev20261028 macOS arm64 wheel, with this PR's image_ops_impl.py and image_ops_test.py copied in:

  • Full image_ops_test.py, with and without this change: no new failures. In both runs, 90 tests error because the wheel doesn't ship the image test-data files, and FormatTest.testError fails; neither touches this code.

  • ResizeImageWithPadV1Test and ResizeImageWithPadV2Test, including testShapeInference in graph mode: pass. With the old image_ops_impl.py, the new test fails in both classes.

  • resize_with_pad inside tf.function with unknown height, width and target sizes, under jit_compile=True, with uint8 input, and through tf.compat.v1.image.resize_image_with_pad: correct output.

  • pylint --rcfile=tensorflow/tools/ci_build/pylintrc: no new messages.

I did not test on GPU. The change only affects the size arithmetic in Python, so the output now differs only where float32 used to round wrongly. I added a RELEASE.md entry because those outputs change.

`resize_with_pad` scales the image by
min(target_width / width, target_height / height) and pads the rest.
It computed that scale in float32, then took `floor(height / ratio)`.
When the scaled size is a whole number, float32 often lands just below
it, so the floor drops a row or column: the image is resized one pixel
short and padded with a line of zeros. For example 512x512 to 224x224
gives a 223x223 image with a black border, and 480x640 to 300x300 gets
a black right-hand column. The padding computed from the same float
can also be one less than intended, shifting the image off center.

Compute the resized size as min(target, size * other_target //
other_size) and the padding as floor((target - scaled size) / 2) with
int64 arithmetic. These are the same formulas as before, evaluated
exactly; on 200,000 random size combinations they match exact rational
arithmetic everywhere, while the float32 version differed in about 5%.

Add a test with sizes that used to get the extra padding.
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Oct 31, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 31, 2026 09:24
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 31, 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 tf.image.resize_with_pad to compute the resized size and padding using exact integer arithmetic (with int64) instead of float32. This prevents rounding issues where the scaled size could land slightly below a whole number, which previously caused the image to be scaled one pixel short and padded with zeros or placed off-center. Unit tests have been added to verify the correct padding behavior under these rounding conditions. I have no feedback to provide as the implementation is correct and well-tested.

@nithyak0204 nithyak0204 self-assigned this Nov 2, 2026
@nithyak0204
nithyak0204 requested a review from a team November 2, 2026 05:17
@nithyak0204 nithyak0204 added comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Nov 2, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Nov 2, 2026
@nithyak0204

Copy link
Copy Markdown

Hi @bodapatisaikrishna, Can you please resolve the conflicts? Thank you!

@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 float32 rounding inaccuracy in tf.image.resize_with_pad! Using int64 floor division cleanly resolves both the dropped row or column and the off-center padding bugs. Please address these three items:

  1. Cover horizontal padding (p_width > 0) and off-center padding rounding in _assertNoExtraPaddingFromRounding (tensorflow/python/ops/image_ops_test.py:3986-4006):
    All three test tuples currently have height <= width, so pad_left and pad_right are always 0. That leaves the positive horizontal-padding path (resized_width < target_width and p_width > 0 in tensorflow/python/ops/image_ops_impl.py:1873-1885) untested. Also, the old float32 code produced the same p_height and p_width on those three tuples, so off-center padding is not tested. Please add a portrait tuple (height > width) and tuples where float32 shifted p_height and p_width off center, and update the docstring:

    def _assertNoExtraPaddingFromRounding(test, resize_image_with_pad):
      """Checks resized size and centering when float32 rounding used to be off.
    
      For these sizes float32 used to land slightly below a whole number for the
      scaled size or padding offset, either dropping an image row/column and
      replacing it with zeros (e.g. 512x512 -> 224x224) or shifting the image
      one pixel off center (e.g. 39x65 -> 100x100 or 78x65 -> 300x300).
    
      Args:
        test: The test case.
        resize_image_with_pad: Called as `resize_image_with_pad(image,
          target_height, target_width, use_tensor_inputs)`.
      """
      # (height, width, target_height, target_width, pad_top, pad_bottom,
      #  pad_left, pad_right)
      for (height, width, target_height, target_width, pad_top, pad_bottom,
           pad_left, pad_right) in [
               (512, 512, 224, 224, 0, 0, 0, 0),
               (480, 640, 300, 300, 37, 38, 0, 0),
               (640, 480, 300, 300, 0, 0, 37, 38),
               (720, 1280, 600, 600, 131, 132, 0, 0),
               (39, 65, 100, 100, 20, 20, 0, 0),
               (78, 65, 300, 300, 0, 0, 25, 25),
           ]:
  2. Reuse the two int64 cross-products and zero constant in _resize_image_with_pad_common (tensorflow/python/ops/image_ops_impl.py:1871-1887):
    i_height * i_target_width and i_width * i_target_height are each evaluated three times, emitting six Mul ops instead of two. Also, math_ops.cast(0, dtypes.int64) is called twice even though constant_op is already imported in this file. Please bind the two products and the int64 zero constant once and reuse them:

        scaled_height = i_height * i_target_width
        scaled_width = i_width * i_target_height
    
        resized_height = math_ops.minimum(
            i_target_height, scaled_height // i_width)
        resized_width = math_ops.minimum(
            i_target_width, scaled_width // i_height)
    
        # floor((target - scaled size) / 2), where the scaled size need not be a
        # whole number.
        zero = constant_op.constant(0, dtype=dtypes.int64)
        p_height = math_ops.maximum(
            zero, (scaled_width - scaled_height) // (2 * i_width))
        p_width = math_ops.maximum(
            zero, (scaled_height - scaled_width) // (2 * i_height))
        p_height = math_ops.cast(p_height, dtype=dtypes.int32)
        p_width = math_ops.cast(p_width, dtype=dtypes.int32)
  3. Rebase onto master and resolve merge conflicts:
    This branch currently has a merge conflict with master, which prevents the automated test suite from running. Please rebase your branch onto the latest master and resolve the conflict.

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Nov 2, 2026
Bind the two int64 cross-products and the zero constant once, which
emits two Mul ops instead of six.

Extend the test with a portrait size, so the horizontal padding path is
covered, and with sizes where float32 shifted the image one pixel off
center (39x65 to 100x100 and 78x65 to 300x300).
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Thanks. Updated in c1b8a6b:

  • Added (640, 480, ...), (39, 65, ...) and (78, 65, ...) to the test and updated the docstring. All six sizes now fail on the old code and pass with this change.
  • The two cross-products and the zero constant are now bound once and reused.
  • I resolved the RELEASE.md conflict by merging the latest master (5f2bbf6) rather than rebasing, and GitHub now reports the PR as mergeable. Let me know if you need a rebased history instead.

@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 items from the previous review round are addressed. Precomputing the two int64 cross-products and the zero constant in tensorflow/python/ops/image_ops_impl.py keeps the graph compact, and the added portrait and off-center padding test cases in tensorflow/python/ops/image_ops_test.py cover the rounding edge cases cleanly. The RELEASE.md conflict is resolved and all automated checks pass. LGTM!

@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 2, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Nov 2, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Nov 3, 2026
@copybara-service
copybara-service Bot merged commit 38d238d into tensorflow:master Nov 3, 2026
19 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Nov 3, 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.resize_with_pad pads a row/column of zeros due to float32 rounding (e.g. 512x512 -> 224x224)

3 participants