Skip to content

[Relax][ONNX][Torch] Add roi_align support and frontend integration#18936

Merged
tlopex merged 2 commits intoapache:mainfrom
LudovicoYIN:relax-roi-align
Mar 26, 2026
Merged

[Relax][ONNX][Torch] Add roi_align support and frontend integration#18936
tlopex merged 2 commits intoapache:mainfrom
LudovicoYIN:relax-roi-align

Conversation

@LudovicoYIN
Copy link
Contributor

Summary

Add Relax roi_align support and wire it through the ONNX and PyTorch frontends.

Changes

  • add relax.vision.roi_align, including attrs, Python wrapper, struct info inference, and legalization
  • add TOPI roi_align compute and keep both legacy and aligned ROIAlign semantics
  • support ONNX RoiAlign, including coordinate_transformation_mode handling for output_half_pixel and half_pixel
  • support PyTorch torchvision.ops.roi_align in the exported-program frontend, including the aligned flag
  • add regression tests for Relax op inference, legalization, TVMScript parsing, ONNX frontend import, and PyTorch frontend import
  • add aligned ROIAlign test coverage to make sure sub-pixel RoIs no longer use the legacy min=1.0 clamp

Validation

  • pytest tests/python/relax/test_op_vision.py -k roi_align
  • pytest tests/python/relax/test_tvmscript_parser_op_vision.py -k roi_align
  • pytest tests/python/relax/test_frontend_onnx.py -k roi_align
  • pytest tests/python/relax/test_frontend_from_exported_program.py -k roi_align

This PR completes the Relax/ONNX/Torch roi_align work tracked in #18928.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, 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 introduces comprehensive support for the ROIAlign operator across the Relax framework, integrating it with both ONNX and PyTorch frontends. The changes enable users to leverage ROIAlign functionality within Relax, ensuring accurate and consistent behavior by addressing different coordinate transformation modes and aligned semantics. This completes a previously tracked work item, expanding Relax's capabilities in computer vision tasks.

Highlights

  • Relax ROIAlign Operator: Added a new relax.vision.roi_align operator, including its attributes (ROIAlignAttrs), Python wrapper, struct info inference, and legalization for both NCHW and NHWC layouts, supporting 'avg' and 'max' modes.
  • ONNX Frontend Integration: Implemented support for the ONNX RoiAlign operator, handling coordinate_transformation_mode (specifically 'half_pixel' and 'output_half_pixel') to correctly map to the aligned flag in Relax.
  • PyTorch Frontend Integration: Integrated support for torchvision.ops.roi_align within the exported-program frontend, correctly interpreting the aligned flag and converting it to the Relax roi_align operator.
  • TOPI Implementation: Enhanced the TOPI roi_align compute logic to incorporate the aligned parameter, ensuring correct handling of both legacy and aligned ROIAlign semantics, particularly regarding the 1-pixel clamp for sub-pixel RoIs.
  • Comprehensive Testing: Added extensive regression tests covering Relax op inference, legalization, TVMScript parsing, and frontend imports for both ONNX and PyTorch, including specific tests for aligned ROIAlign 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.

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.

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
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 introduces the ROIAlign operator to TVM Relax, including its attributes, Python and C++ implementations, legalization rules, and comprehensive tests across ONNX and PyTorch frontends. Review comments suggest improving a misleading error message in the ONNX frontend's RoiAlign converter, ensuring consistency in the default sampling_ratio value in the PyTorch frontend, and addressing potential test fragility due to a dynamically generated variable name in one of the tests.

Comment on lines +2457 to +2461
elif coordinate_transformation_mode != "output_half_pixel":
raise NotImplementedError(
"RoiAlign only supports coordinate_transformation_mode "
"'half_pixel' and 'output_half_pixel'"
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The NotImplementedError message is slightly misleading. It states that RoiAlign only supports 'half_pixel' and 'output_half_pixel', but the else branch implicitly handles 'output_half_pixel' by setting aligned = False. The error should only be raised if coordinate_transformation_mode is neither 'half_pixel' nor 'output_half_pixel'.

Suggested change
elif coordinate_transformation_mode != "output_half_pixel":
raise NotImplementedError(
"RoiAlign only supports coordinate_transformation_mode "
"'half_pixel' and 'output_half_pixel'"
)
elif coordinate_transformation_mode == "output_half_pixel":
aligned = False
else:
raise NotImplementedError(
"RoiAlign only supports coordinate_transformation_mode "
"'half_pixel' and 'output_half_pixel'"
)

Comment on lines +1134 to +1135
sampling_ratio = args[5] if len(args) > 5 else -1
aligned = args[6] if len(args) > 6 else False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The sampling_ratio default value is set to -1 in the roi_align function signature, but here it's 0 in the attr.get call. It's better to be consistent with the Relax op's default value.

Suggested change
sampling_ratio = args[5] if len(args) > 5 else -1
aligned = args[6] if len(args) > 6 else False
sampling_ratio = args[5] if len(args) > 5 else -1

input_1: R.Tensor((1, 1, 4, 4), dtype="float32"),
rois: R.Tensor((1, 5), dtype="float32"),
) -> R.Tuple(R.Tensor((1, 1, 1, 1), dtype="float32")):
R.func_attr({"tir_var_lower_bound": {"s86": 2}})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The tir_var_lower_bound attribute s86 seems to be a dynamically generated variable name. It's generally better to use a more stable or descriptive name for variables in expected IR modules, especially if they are part of assertions. This can prevent test failures if the internal naming convention changes slightly.

Copy link
Member

@tlopex tlopex left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall looks good, please have a look at the comments


_ROI_ALIGN_PYTHON_SPEC = importlib.util.spec_from_file_location(
"roi_align_python",
Path(__file__).resolve().parents[3] / "python/tvm/topi/testing/roi_align_python.py",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This import is a bit indirect. Since roi_align_python.py is already under tvm.topi.testing, it would be cleaner to import roi_align_nchw_python directly instead of loading it via importlib and a file path.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the indirect importlib-based loading from test_op_vision.py.

tvm.testing.assert_allclose(result.numpy(), expected, rtol=1e-5, atol=1e-5)


def test_roi_align_legalize_e2e_aligned():
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since e2e tests add too much CI pressure, I suggest do not include those e2e tests here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the roi_align e2e tests from test_op_vision.py to keep the op-level test coverage lighter. The end-to-end numerical coverage is still exercised through the ONNX and PyTorch frontend tests, including the aligned path.

@LudovicoYIN
Copy link
Contributor Author

@tlopex. Thanks for the review. I've addressed the comments by simplifying the op-level tests and cleaning up the frontend handling.

@LudovicoYIN LudovicoYIN requested a review from tlopex March 26, 2026 14:12
Copy link
Member

@tlopex tlopex left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks!

@tlopex tlopex merged commit 1e08eb2 into apache:main Mar 26, 2026
11 checks passed
@LudovicoYIN LudovicoYIN deleted the relax-roi-align branch March 26, 2026 15:16
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