Skip to content

[BugFix][TOPI] Fix resize accuracy with non-floor rounding#18835

Closed
tqchen wants to merge 1 commit into
apache:mainfrom
tqchen:reland-resize-fix
Closed

[BugFix][TOPI] Fix resize accuracy with non-floor rounding#18835
tqchen wants to merge 1 commit into
apache:mainfrom
tqchen:reland-resize-fix

Conversation

@tqchen

@tqchen tqchen commented Feb 26, 2026

Copy link
Copy Markdown
Member

Fixes a resize accuracy bug where can_convert_multiply_to_intdiv optimization was applied unconditionally for nearest_neighbor + asymmetric mode, even when the rounding method is not floor. This caused incorrect output for round/ceil rounding when target dimensions are integer multiples of source dimensions.

The fix guards the optimization to only apply when rounding_method is floor or empty (default).

Also updates the reference implementation in resize_python.py to properly handle non-floor rounding methods.

Based on #16137.

`can_convert_multiply_to_intdiv` was enabled unconditionally for
`nearest_neighbor` + `asymmetric` mode, even when `rounding_method` is
not `floor`.  This converted the mapped coordinate via integer division
(equivalent to floor) regardless of the requested rounding, producing
wrong results whenever the target size is an exact integer multiple of
the source size.

Fix: guard the `can_convert_multiply_to_intdiv` optimisation so it only
activates when `rounding_method` is `"floor"` or `""` (which defaults to
`"floor"` for asymmetric mode).

Also update the Python reference implementation (`resize_python.py`) to
accept and thread a `rounding_method` parameter through all public entry
points (`get_index`, `resize3d_nearest`, `resize3d_ncdhw`, `resize1d_python`,
`resize2d_python`, `resize3d_python`), so the reference matches the
corrected TVM behaviour.

Add `tests/python/te/test_topi_resize2d.py` with regression tests that
exercise the buggy path (non-floor rounding + asymmetric + integer
scale factor) as well as sanity checks for floor rounding and
non-integer scale factors.

Fixes: apache#16137
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @tqchen, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves an accuracy issue in the image resize operation, specifically for the nearest_neighbor method with asymmetric coordinate transformation. The core problem stemmed from an optimization being applied too broadly, leading to incorrect output when non-floor rounding methods were used. The fix ensures that this optimization is now correctly guarded, and the reference implementation has been enhanced to accurately reflect the intended rounding behaviors.

Highlights

  • Bug Fix: Resize Accuracy: Addressed a bug in the nearest_neighbor resize method with asymmetric coordinate transformation where the can_convert_multiply_to_intdiv optimization was incorrectly applied for non-floor rounding methods.
  • Conditional Optimization: The can_convert_multiply_to_intdiv optimization is now conditionally applied only when the rounding_method is 'floor' or unspecified, preventing inaccurate results for 'round' or 'ceil' rounding when target dimensions are integer multiples of source dimensions.
  • Reference Implementation Update: The Python reference implementation in resize_python.py has been updated to correctly handle and propagate various non-floor rounding methods, ensuring consistency with the fixed behavior.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • python/tvm/topi/image/resize.py
    • Introduced a conditional check to ensure the can_convert_multiply_to_intdiv optimization is only applied when the rounding_method is 'floor' or unspecified, preventing incorrect behavior with other rounding methods.
  • python/tvm/topi/testing/resize_python.py
    • Modified the get_index function to correctly handle various rounding_method parameters, including 'round', 'round_prefer_floor', 'round_prefer_ceil', and 'ceil'.
    • Updated the resize3d_nearest function to pass the rounding_method parameter to get_index.
    • Extended the resize3d_ncdhw function signature to include a rounding_method parameter and propagated it to internal calls.
    • Introduced rounding_method as a parameter to resize1d_python, resize2d_python, and resize3d_python and forwarded it to the underlying resize functions.
Activity
  • No human activity has occurred on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@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 fixes a bug in the resize operator where an optimization was incorrectly applied for non-floor rounding methods. The fix correctly guards this optimization. The PR also updates the Python reference implementation to support different rounding methods. My review found some issues in the updated reference implementation in resize_python.py, where the rounding logic did not correctly match the TVM operator for all cases, and it handled unknown rounding methods differently. I've provided a suggestion to fix these issues in the test helper function to ensure its correctness and consistency with the main operator.

Comment on lines +44 to 63
def get_index(x, image_width, target_width, coordinate_transformation_mode, rounding_method=""):
"""get and round the nearest index for nearest_neighbor"""
in_x = get_inx(x, image_width, target_width, coordinate_transformation_mode)
if coordinate_transformation_mode == "align_corners":
# round prefer ceil
if rounding_method == "" or rounding_method == "floor":
if coordinate_transformation_mode == "align_corners":
out = math.floor(in_x + 0.5)
else:
out = math.floor(in_x)
elif rounding_method == "round":
out = math.floor(in_x + 0.5)
elif rounding_method == "round_prefer_floor":
out = math.ceil(in_x - 0.5)
elif rounding_method == "round_prefer_ceil":
out = math.floor(in_x + 0.5)
elif rounding_method == "ceil":
out = math.ceil(in_x)
else:
out = math.floor(in_x)
out = max(min(out, image_width - 1), 0)
return out

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.

high

The implementation of get_index has a few issues that could lead to incorrect test results or mask bugs:

  1. Incorrect Rounding for "round" method: The logic for rounding_method="round" uses math.floor(in_x + 0.5), which is "round half up". The TVM operator te.round implements "round half to even". The reference implementation should use Python's built-in round() to match this behavior. This also affects the default behavior for coordinate_transformation_mode="align_corners".
  2. Incorrect logic for "floor" method: When rounding_method="floor" and coordinate_transformation_mode="align_corners", the current code applies "round half up" instead of flooring. The TVM operator does not alter the rounding method if it's explicitly provided.
  3. Inconsistent Error Handling: Unknown rounding methods silently fall back to floor. This differs from the main operator, which raises a ValueError. The test helper should also raise an error to detect invalid inputs.
  4. Return Type: The function returns a float for an index, which is less precise. It should return an int.

I suggest refactoring the function to align with the TVM operator's logic, which will fix these issues and improve clarity.

def get_index(x, image_width, target_width, coordinate_transformation_mode, rounding_method=""):
    """get and round the nearest index for nearest_neighbor"""
    in_x = get_inx(x, image_width, target_width, coordinate_transformation_mode)

    effective_rounding_method = rounding_method
    if not effective_rounding_method:
        if coordinate_transformation_mode == "align_corners":
            effective_rounding_method = "round"
        else:
            effective_rounding_method = "floor"

    if effective_rounding_method == "floor":
        out = math.floor(in_x)
    elif effective_rounding_method == "round":
        # Use python's built-in round to match te.round (round half to even)
        out = round(in_x)
    elif effective_rounding_method == "round_prefer_floor":
        out = math.ceil(in_x - 0.5)
    elif effective_rounding_method == "round_prefer_ceil":
        out = math.floor(in_x + 0.5)
    elif effective_rounding_method == "ceil":
        out = math.ceil(in_x)
    else:
        raise ValueError(f"Unknown rounding method: {rounding_method!r}")

    out = max(min(out, image_width - 1), 0)
    return int(out)

@tqchen tqchen closed this Feb 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant