Skip to content

[Relax][PyTroch] Add randn.default and randn_like.default support#18815

Merged
mshr-h merged 1 commit intoapache:mainfrom
guan404ming:feat/pytorch-frontend-randn-support
Feb 24, 2026
Merged

[Relax][PyTroch] Add randn.default and randn_like.default support#18815
mshr-h merged 1 commit intoapache:mainfrom
guan404ming:feat/pytorch-frontend-randn-support

Conversation

@guan404ming
Copy link
Member

Why

PyTorch models using torch.randn() or torch.randn_like() fail to convert via from_exported_program (part of #18476).

How

  • Add _randn and _randn_like handlers that emit constant tensors sampled
  • Add tests verifying conversion produces correct output shape and dtype

@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 addresses a critical issue where PyTorch models utilizing torch.randn() or torch.randn_like() failed to convert properly using the from_exported_program utility. By introducing specific handlers for these operations, the PR ensures that models incorporating random number generation can now be successfully translated, improving the compatibility and robustness of the conversion process.

Highlights

  • PyTorch randn and randn_like support: Implemented handlers for torch.randn() and torch.randn_like() operations to enable their conversion via from_exported_program.
  • Test coverage: Added dedicated test cases to verify the correct conversion and output shape/dtype for randn and randn_like operations.

🧠 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/relax/frontend/torch/exported_program_translator.py
    • Added _randn method to handle torch.randn operations, emitting constant tensors sampled using NumPy.
    • Added _randn_like method to handle torch.randn_like operations, determining shape and dtype from the input tensor.
    • Registered randn.default and randn_like.default with their respective new handlers in the create_convert_map.
  • tests/python/relax/test_frontend_from_exported_program.py
    • Added test_randn to verify the conversion of a model using torch.randn and assert its output shape and dtype.
    • Added test_randn_like to verify the conversion of a model using torch.randn_like and assert its output shape and dtype.
Activity
  • No human activity has been recorded 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.

Signed-off-by: Guan-Ming Chiu <guanmingchiu@gmail.com>
@guan404ming guan404ming force-pushed the feat/pytorch-frontend-randn-support branch from a2d36fc to bdf8da8 Compare February 23, 2026 18:51
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 torch.randn and torch.randn_like in the PyTorch frontend by emitting constant tensors. This is a solid approach for handling these operations during model import. The accompanying tests correctly verify the output shape and data type for static shapes.

My main feedback concerns the handling of dynamic shapes. The current implementations for _randn and _randn_like will fail if they encounter symbolic dimensions, as they rely on numpy which requires concrete shapes. I've suggested adding explicit checks to raise a NotImplementedError in such cases to prevent crashes and make the limitation clear.

Comment on lines +994 to +1003
def _randn(self, node: fx.Node) -> relax.Var:
import numpy as np

args = self.retrieve_args(node)
size = args[0] if isinstance(args[0], (list, tuple)) else (args[0],)
dtype = self._convert_data_type(
node.kwargs.get("dtype", torch.get_default_dtype()), self.env
)
data = np.random.randn(*size).astype(dtype)
return self.block_builder.emit(relax.const(data, dtype))
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This implementation of _randn will fail if size contains symbolic dimensions (i.e., tir.Var from torch.export.Dim), as np.random.randn requires concrete integer shapes. To prevent a crash with dynamic shapes, it's better to add an explicit check and raise a NotImplementedError.

Suggested change
def _randn(self, node: fx.Node) -> relax.Var:
import numpy as np
args = self.retrieve_args(node)
size = args[0] if isinstance(args[0], (list, tuple)) else (args[0],)
dtype = self._convert_data_type(
node.kwargs.get("dtype", torch.get_default_dtype()), self.env
)
data = np.random.randn(*size).astype(dtype)
return self.block_builder.emit(relax.const(data, dtype))
def _randn(self, node: fx.Node) -> relax.Var:
import numpy as np
args = self.retrieve_args(node)
size = args[0] if isinstance(args[0], (list, tuple)) else (args[0],)
if any(isinstance(s, tir.Var) for s in size):
raise NotImplementedError("torch.randn with dynamic shapes is not supported yet.")
dtype = self._convert_data_type(
node.kwargs.get("dtype", torch.get_default_dtype()), self.env
)
data = np.random.randn(*size).astype(dtype)
return self.block_builder.emit(relax.const(data, dtype))

Copy link
Member Author

Choose a reason for hiding this comment

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

int(s) will already raise a TypeError with a clear message. Adding explicit checks here would be inconsistent with the rest of the codebase.

Comment on lines +1005 to 1015
def _randn_like(self, node: fx.Node) -> relax.Var:
import numpy as np

x = self.env[node.args[0]]
x_sinfo = x.struct_info
shape = [int(s) for s in x_sinfo.shape]
dtype = self._convert_data_type(node.kwargs.get("dtype", None) or x_sinfo.dtype, self.env)
data = np.random.randn(*shape).astype(dtype)
return self.block_builder.emit(relax.const(data, dtype))

def _zeros(self, node: fx.Node) -> relax.Var:
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Similar to _randn, this implementation for _randn_like does not support dynamic shapes. The line shape = [int(s) for s in x_sinfo.shape] will raise a TypeError if any shape dimension s is a symbolic tir.Var. Please add a check to handle this case gracefully.

Suggested change
def _randn_like(self, node: fx.Node) -> relax.Var:
import numpy as np
x = self.env[node.args[0]]
x_sinfo = x.struct_info
shape = [int(s) for s in x_sinfo.shape]
dtype = self._convert_data_type(node.kwargs.get("dtype", None) or x_sinfo.dtype, self.env)
data = np.random.randn(*shape).astype(dtype)
return self.block_builder.emit(relax.const(data, dtype))
def _zeros(self, node: fx.Node) -> relax.Var:
def _randn_like(self, node: fx.Node) -> relax.Var:
import numpy as np
x = self.env[node.args[0]]
x_sinfo = x.struct_info
if any(isinstance(s, tir.Var) for s in x_sinfo.shape):
raise NotImplementedError("torch.randn_like with dynamic shapes is not supported yet.")
shape = [int(s) for s in x_sinfo.shape]
dtype = self._convert_data_type(
node.kwargs.get("dtype", None) or x_sinfo.dtype, self.env
)
data = np.random.randn(*shape).astype(dtype)
return self.block_builder.emit(relax.const(data, dtype))

Copy link
Member Author

Choose a reason for hiding this comment

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

Ditto

@guan404ming guan404ming marked this pull request as ready for review February 24, 2026 04:15
@guan404ming
Copy link
Member Author

cc @tlopex @mshr-h

@mshr-h mshr-h merged commit 6d46fa7 into apache:main Feb 24, 2026
13 checks passed
@guan404ming
Copy link
Member Author

Thanks!

@guan404ming guan404ming deleted the feat/pytorch-frontend-randn-support branch February 24, 2026 16:03
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