Skip to content

Conversation

@locnd182644
Copy link
Contributor

This PR supported Local Response Normalization operator for ONNX.

Description

Implement and Test Local Response Normalization operator for ONNX frontend.

Implement

  • Using avg_pool operator to compute LRN
  • Pseudocode:
def local_response_norm(input, size, alpha, beta, k):
    dim = input.dim()
    check_only_support_3D_4D()
    div = input.mul(input)
    div = expand_dim(div, 1)
    pad_len = size // 2
    if dim == 3:
        div = avg_pool2d(div,
                        (size, 1),
                        stride=1,
                        padding=(pad_len, 0, pad_len, 0))
    else:
        div = avg_pool3d(div,
                        (size, 1, 1),
                        stride=1,
                        padding=(pad_len, 0, 0, pad_len, 0, 0))

    div = squeeze_dim(div, 1)
    div = div.mul(alpha).add(k).pow(beta)
    return input / div

Reference

Implement same as Pytorch: https://discuss.pytorch.org/t/why-use-avgpool2d-and-avgpool3d-in-local-response-norm/97236

- Implement Local Response Norm Operator
- Test LRN Node
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @locnd182644, 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 significantly enhances the ONNX frontend's capabilities by introducing support for the Local Response Normalization (LRN) operator. This addition allows the Relax framework to seamlessly import and execute ONNX models that incorporate LRN layers, thereby broadening its compatibility with various neural network architectures. The implementation carefully translates the LRN operation into Relax expressions, utilizing average pooling for its core computation.

Highlights

  • ONNX LRN Operator Support: Implemented support for the Local Response Normalization (LRN) operator in the ONNX frontend, allowing Relax to process ONNX models containing LRN layers.
  • LRN Implementation Details: The LRN operator is implemented using relax.op.nn.avg_pool2d for 3D inputs and relax.op.nn.avg_pool3d for 4D inputs, following a common approach for LRN computation.
  • Input Dimension Handling: The implementation includes logic to handle both 3D and 4D input tensors, raising a ValueError for unsupported dimensions.
  • New Test Case: A new test case, test_local_response_norm, has been added to tests/python/relax/test_frontend_onnx.py to verify the correctness of the LRN operator conversion.

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

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
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 adds support for the ONNX Local Response Normalization (LRN) operator to the Relax frontend. The implementation correctly uses average pooling for the normalization computation and includes a corresponding test case. My review focuses on improving robustness by addressing potential data type mismatches and handling of dynamic input shapes. I've also suggested enhancing the test coverage to include more scenarios.

Comment on lines +2413 to +2419
if hasattr(data.struct_info, "ndim"):
ndim = data.struct_info.ndim
else:
ndim = len(data.struct_info.shape)

if ndim not in [3, 4]:
raise ValueError(f"LRN only supports 3D or 4D input, got {ndim}D.")
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The current logic for determining the input tensor's rank does not handle cases where the rank is unknown (ndim == -1). This could lead to incorrect behavior or errors when processing models with dynamic-rank tensors, as the code would default to the 4D logic path. It's better to explicitly check for an unknown rank and raise an error. Using data.struct_info.ndim directly is also a cleaner way to get the rank.

Suggested change
if hasattr(data.struct_info, "ndim"):
ndim = data.struct_info.ndim
else:
ndim = len(data.struct_info.shape)
if ndim not in [3, 4]:
raise ValueError(f"LRN only supports 3D or 4D input, got {ndim}D.")
ndim = data.struct_info.ndim
if ndim == -1:
raise ValueError("The input tensor to LRN must have a known rank.")
if ndim not in [3, 4]:
raise ValueError(f"LRN only supports 3D or 4D input, got {ndim}D.")

Comment on lines +2448 to +2450
const_alpha = relax.const(alpha, dtype="float32")
const_bias = relax.const(bias, dtype="float32")
const_beta = relax.const(beta, dtype="float32")
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The data type for the alpha, bias, and beta constants is hardcoded to float32. The ONNX LRN operator supports various floating-point types (e.g., float16, float64). Hardcoding the dtype can cause type mismatches or precision loss if the input tensor has a different float dtype. These constants should use the same data type as the input tensor data.

Suggested change
const_alpha = relax.const(alpha, dtype="float32")
const_bias = relax.const(bias, dtype="float32")
const_beta = relax.const(beta, dtype="float32")
const_alpha = relax.const(alpha, dtype=data.struct_info.dtype)
const_bias = relax.const(bias, dtype=data.struct_info.dtype)
const_beta = relax.const(beta, dtype=data.struct_info.dtype)

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