Skip to content

[Relax][PyTorch] Enhance scale_factor handling in interpolation#18550

Merged
mshr-h merged 1 commit intoapache:mainfrom
guan404ming:enhance-scale-factor
Dec 6, 2025
Merged

[Relax][PyTorch] Enhance scale_factor handling in interpolation#18550
mshr-h merged 1 commit intoapache:mainfrom
guan404ming:enhance-scale-factor

Conversation

@guan404ming
Copy link
Copy Markdown
Member

Why

Fixes interpolation to support different scaling factors for height and width (e.g., scale_factor=[2.0, 3.0])

How

  • Removed the bug: Stopped extracting just the first element ([0]) from scale_factor lists
  • Passed full value: Now passes the entire scale_factor (scalar or list) to the underlying implementation, which already handles both correctly

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @guan404ming, 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 addresses a critical bug in the relax frontend's handling of PyTorch interpolation operations, specifically concerning the scale_factor parameter. Previously, the system would incorrectly process scale_factor lists by only considering the first element, thereby preventing proper non-uniform scaling. The fix ensures that the complete scale_factor value, whether a scalar or a list, is correctly propagated to the underlying implementation, enabling accurate and flexible interpolation for varying height and width dimensions.

Highlights

  • Corrected scale_factor handling: The pull request fixes an issue where scale_factor in PyTorch interpolation was incorrectly handled, specifically when it was a list or tuple for different height and width scaling.
  • Removed erroneous extraction: The previous code incorrectly extracted only the first element from scale_factor lists, leading to incorrect scaling for non-uniform dimensions in _upsample_nearest2d and _upsample_bicubic2d.
  • Direct scale_factor passing: The change now passes the entire scale_factor (scalar or list) directly to the underlying _upsample_impl function, which is designed to handle both formats correctly.
  • Expanded test coverage: New tests have been added to test_frontend_from_exported_program.py to validate the correct behavior of nearest, bilinear, and bicubic interpolation modes with both scalar and list scale_factor inputs.
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.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

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 correctly fixes a bug in the PyTorch frontend where interpolation with a list scale_factor was handled incorrectly, preventing different scaling for height and width. The change removes the faulty indexing and passes the scale_factor directly to the underlying implementation, which is the correct approach. The addition of numerical tests for nearest, bilinear, and bicubic modes with both scalar and list scale factors is a great way to ensure correctness. I've suggested a refactoring for the new test to reduce code duplication and improve maintainability using pytest.mark.parametrize.

Comment on lines +4903 to +4962
def test_interpolate_scale_factor_list():
class InterpolateNearestScalar(Module):
"""Nearest interpolation with scalar scale_factor."""

def forward(self, input):
return torch.nn.functional.interpolate(input, scale_factor=2.0, mode="nearest")

class InterpolateNearestList(Module):
"""Nearest interpolation with list scale_factor (different H and W scaling)."""

def forward(self, input):
return torch.nn.functional.interpolate(input, scale_factor=[2.0, 3.0], mode="nearest")

class InterpolateBilinearScalar(Module):
"""Bilinear interpolation with scalar scale_factor."""

def forward(self, input):
return torch.nn.functional.interpolate(
input, scale_factor=2.0, mode="bilinear", align_corners=False
)

class InterpolateBilinearList(Module):
"""Bilinear interpolation with list scale_factor (different H and W scaling)."""

def forward(self, input):
return torch.nn.functional.interpolate(
input, scale_factor=[2.0, 3.0], mode="bilinear", align_corners=False
)

class InterpolateBicubicScalar(Module):
"""Bicubic interpolation with scalar scale_factor."""

def forward(self, input):
return torch.nn.functional.interpolate(
input, scale_factor=2.0, mode="bicubic", align_corners=False
)

class InterpolateBicubicList(Module):
"""Bicubic interpolation with list scale_factor (different H and W scaling)."""

def forward(self, input):
return torch.nn.functional.interpolate(
input, scale_factor=[2.0, 3.0], mode="bicubic", align_corners=False
)

# Test with 32x32 input
example_args = (torch.randn(1, 3, 32, 32, dtype=torch.float32),)

# Test nearest mode with scalar and list scale_factor
verify_model_numerically(InterpolateNearestScalar(), example_args, rtol=1e-5, atol=1e-5)
verify_model_numerically(InterpolateNearestList(), example_args, rtol=1e-5, atol=1e-5)

# Test bilinear mode with scalar and list scale_factor
verify_model_numerically(InterpolateBilinearScalar(), example_args, rtol=1e-5, atol=1e-5)
verify_model_numerically(InterpolateBilinearList(), example_args, rtol=1e-5, atol=1e-5)

# Test bicubic mode with scalar and list scale_factor
verify_model_numerically(InterpolateBicubicScalar(), example_args, rtol=1e-5, atol=1e-5)
verify_model_numerically(InterpolateBicubicList(), example_args, rtol=1e-5, atol=1e-5)

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

This test is great for covering the different interpolation modes with both scalar and list scale_factors. However, there's a lot of repeated code between the different test cases. You can significantly simplify this by using pytest.mark.parametrize to iterate through the different modes and scale factors. This will make the test more concise and easier to maintain or extend in the future.

@pytest.mark.parametrize(
    "mode, scale_factor",
    [
        ("nearest", 2.0),
        ("nearest", [2.0, 3.0]),
        ("bilinear", 2.0),
        ("bilinear", [2.0, 3.0]),
        ("bicubic", 2.0),
        ("bicubic", [2.0, 3.0]),
    ],
)
def test_interpolate_scale_factor_list(mode, scale_factor):
    """Test interpolation with various modes and scale factors."""

    class InterpolateModel(Module):
        def forward(self, input_tensor):
            kwargs = {"scale_factor": scale_factor, "mode": mode}
            if mode != "nearest":
                kwargs["align_corners"] = False
            return torch.nn.functional.interpolate(input_tensor, **kwargs)

    # Test with 32x32 input
    example_args = (torch.randn(1, 3, 32, 32, dtype=torch.float32),)
    verify_model_numerically(InterpolateModel(), example_args, rtol=1e-5, atol=1e-5)

@guan404ming guan404ming marked this pull request as ready for review December 6, 2025 02:56
@guan404ming
Copy link
Copy Markdown
Member Author

cc. @tlopex @mshr-h

Comment thread tests/python/relax/test_frontend_from_exported_program.py Outdated
@mshr-h mshr-h merged commit 6cf49e6 into apache:main Dec 6, 2025
13 checks passed
@guan404ming guan404ming deleted the enhance-scale-factor branch December 6, 2025 11:45
@guan404ming
Copy link
Copy Markdown
Member Author

Thanks!

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.

2 participants