You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "guan404ming (via GitHub)" <gi...@apache.org> on 2026/02/23 18:47:37 UTC

[PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

guan404ming opened a new pull request, #18815:
URL: https://github.com/apache/tvm/pull/18815

   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


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #18815:
URL: https://github.com/apache/tvm/pull/18815#issuecomment-3953144265

   Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on PR #18815:
URL: https://github.com/apache/tvm/pull/18815#issuecomment-3948879463

   cc @tlopex @mshr-h


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #18815:
URL: https://github.com/apache/tvm/pull/18815#issuecomment-3946632881

   ## Summary of Changes
   
   Hello @guan404ming, I'm Gemini Code Assist[^1]! 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](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
   
   <details>
   <summary><b>Changelog</b></summary>
   
   * **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.
   </details>
   
   <details>
   <summary><b>Activity</b></summary>
   
   * No human activity has been recorded on this pull request yet.
   </details>
   
   <details>
   <summary><b>Using Gemini Code Assist</b></summary>
   <br>
   
   The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
   
   <b>Invoking Gemini</b>
   
   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.
   
   <b>Customization</b>
   
   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](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
   
   <b>Limitations & Feedback</b>
   
   Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: 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](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
   
   <b>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](https://cloud.google.com/products/gemini/code-assist).</b>
   </details>
   
   
   [^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

Posted by "mshr-h (via GitHub)" <gi...@apache.org>.
mshr-h merged PR #18815:
URL: https://github.com/apache/tvm/pull/18815


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

Posted by "guan404ming (via GitHub)" <gi...@apache.org>.
guan404ming commented on code in PR #18815:
URL: https://github.com/apache/tvm/pull/18815#discussion_r2842540206


##########
python/tvm/relax/frontend/torch/exported_program_translator.py:
##########
@@ -991,6 +991,27 @@ def _hamming_window(self, node: fx.Node) -> relax.Var:
             relax.op.hamming_window(window_size, periodic, alpha, beta, 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],)
+        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))

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



##########
python/tvm/relax/frontend/torch/exported_program_translator.py:
##########
@@ -991,6 +991,27 @@ def _hamming_window(self, node: fx.Node) -> relax.Var:
             relax.op.hamming_window(window_size, periodic, alpha, beta, 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],)
+        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_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:

Review Comment:
   Ditto



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org


Re: [PR] [Relax][PyTroch] Add randn.default and randn_like.default support [tvm]

Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #18815:
URL: https://github.com/apache/tvm/pull/18815#discussion_r2842511057


##########
python/tvm/relax/frontend/torch/exported_program_translator.py:
##########
@@ -991,6 +991,27 @@ def _hamming_window(self, node: fx.Node) -> relax.Var:
             relax.op.hamming_window(window_size, periodic, alpha, beta, 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],)
+        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))

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   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`.
   
   ```suggestion
       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))
   ```



##########
python/tvm/relax/frontend/torch/exported_program_translator.py:
##########
@@ -991,6 +991,27 @@ def _hamming_window(self, node: fx.Node) -> relax.Var:
             relax.op.hamming_window(window_size, periodic, alpha, beta, 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],)
+        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_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:

Review Comment:
   ![high](https://www.gstatic.com/codereviewagent/high-priority.svg)
   
   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.
   
   ```suggestion
       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))
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org