Skip to content

Conversation

@guan404ming
Copy link
Member

Why

ONNX models use the Size operator to get total element count of a tensor. Relax didn't have a native equivalent.

How

  • Adds R.size(tensor) operator that returns the total number of elements in a tensor as a scalar int64

@gemini-code-assist
Copy link
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 enhances the Relax framework by introducing a dedicated native operator, relax.op.size, designed to efficiently calculate the total number of elements within a tensor. This addition streamlines the conversion of ONNX models by providing a direct equivalent for the ONNX Size operator, eliminating the need for a multi-step workaround. The change also includes the necessary backend implementation, operator registration, and a legalization rule to ensure seamless integration and functionality within the Relax compilation pipeline, along with new tests to validate its behavior.

Highlights

  • New Native Operator: Introduced a new native relax.op.size operator that computes the total number of elements in a tensor, returning a scalar int64.
  • ONNX Frontend Integration: Updated the ONNX frontend to utilize the new relax.op.size operator, replacing the previous workaround that involved prod(shape_to_tensor(shape_of(input))) for the ONNX Size operator.
  • Operator Legalization: Added a legalization rule for relax.size which maps it to op.prod(op.shape_to_tensor(op.shape_of(call.args[0]))), ensuring proper lowering and compilation.
  • C++ Backend Implementation: Implemented the C++ backend for the relax.size operator, including its InferStructInfoSize for type inference and registration within the TVM FFI.
  • Comprehensive Testing: Added new Python unit tests (test_op_size.py) to verify the correctness of the relax.op.size operator for both static and dynamic tensor shapes.

🧠 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 introduces a native R.size(tensor) operator in Relax, which computes the total number of elements in a tensor. This is a useful addition, especially for ONNX model compatibility.

The changes are well-structured:

  • A new relax.size operator is defined in C++ with struct info inference that correctly returns a scalar int64.
  • The operator is exposed to Python via FFI.
  • A legalization rule is added to lower relax.size to a sequence of existing ops (prod, shape_of, shape_to_tensor), which is a good design choice for reusing existing infrastructure.
  • The ONNX frontend is updated to use the new native operator.
  • New tests are added for both static and dynamic shapes.

Overall, this is a solid contribution. I've added one suggestion to enhance the test coverage by including edge cases like scalar tensors and tensors with zero-sized dimensions.

Comment on lines +1 to +63
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

import numpy as np

import tvm
import tvm.testing
from tvm import relax
from tvm.script import relax as R


def test_op_size():
@tvm.script.ir_module
class Module:
@R.function
def main(x: R.Tensor((2, 3), "float32")) -> R.Tensor((), "int64"):
return R.size(x)

x_np = np.random.rand(2, 3).astype("float32")
x = tvm.runtime.tensor(x_np)

target = tvm.target.Target("llvm")
ex = relax.build(Module, target)
vm = relax.VirtualMachine(ex, tvm.cpu())

res = vm["main"](x)
assert res.numpy() == 6


def test_op_size_dynamic():
@tvm.script.ir_module
class Module:
@R.function
def main(x: R.Tensor(("m", "n"), "float32")) -> R.Tensor((), "int64"):
return R.size(x)

x_np = np.random.rand(4, 5).astype("float32")
x = tvm.runtime.tensor(x_np)

target = tvm.target.Target("llvm")
ex = relax.build(Module, target)
vm = relax.VirtualMachine(ex, tvm.cpu())

res = vm["main"](x)
assert res.numpy() == 20


if __name__ == "__main__":
tvm.testing.main()
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 current tests cover static and dynamic shapes, which is great. To make the test suite more robust, consider adding tests for a few edge cases:

  1. Scalar input (0-dimensional tensor): The size should be 1.
  2. Tensor with a zero-sized dimension: The size should be 0.

Here are some examples of how you could write these tests:

def test_op_size_scalar():
    @tvm.script.ir_module
    class Module:
        @R.function
        def main(x: R.Tensor((), "float32")) -> R.Tensor((), "int64"):
            return R.size(x)

    x_np = np.array(1.0, dtype="float32")
    x = tvm.runtime.tensor(x_np)

    target = tvm.target.Target("llvm")
    ex = relax.build(Module, target)
    vm = relax.VirtualMachine(ex, tvm.cpu())

    res = vm["main"](x)
    assert res.numpy() == 1

def test_op_size_zero_dim():
    @tvm.script.ir_module
    class Module:
        @R.function
        def main(x: R.Tensor((2, 0, 3), "float32")) -> R.Tensor((), "int64"):
            return R.size(x)

    x_np = np.empty((2, 0, 3), dtype="float32")
    x = tvm.runtime.tensor(x_np)

    target = tvm.target.Target("llvm")
    ex = relax.build(Module, target)
    vm = relax.VirtualMachine(ex, tvm.cpu())

    res = vm["main"](x)
    assert res.numpy() == 0

@guan404ming guan404ming marked this pull request as ready for review January 16, 2026 13:44
@guan404ming
Copy link
Member Author

cc @tlopex @mshr-h

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