<jupyter_start><jupyter_text>Exporting a PyTorch model to ONNX natively using PyTorch. _Note: This example borrows from a PyTorch sample test used in BentoML_ Section 1: Create a simple PyTorch model.  Section 1.1: Import the packages we need:<jupyter_code>import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np<jupyter_output><empty_output><jupyter_text>Section 1.2: Build a simple model using the PyTorch function capability.<jupyter_code>class Net(nn.Module):
    def __init__(self):
        super().__init__()

        self.linear = nn.Linear(5, 1, bias=False)
        torch.nn.init.ones_(self.linear.weight)

    def forward(self, x):
        x = self.linear(x)

        return x<jupyter_output><empty_output><jupyter_text>Section 1.3: Test our model - it should return a result of 15.<jupyter_code>numpy_data = np.array([[1, 2, 3, 4, 5]], dtype=np.float32)
input_tensor = torch.from_numpy(numpy_data)

my_nn = Net()
result = my_nn(input_tensor)
print (result)<jupyter_output><empty_output><jupyter_text>Section 2: Convert our simple linear model using PyTorch built-in ONNX export capabilities The PyTorch to ONNX export capability is invoked through a Python API as shown here. In our example, a model we created is being exported to ONNX; an existing model can be loaded and exported through the same mechanisms.Details on the full set of ONNX capabilities can be found here: https://pytorch.org/docs/stable/onnx.html<jupyter_code>import torch.onnx

torch.onnx.export(my_nn,                     # model being run
                  input_tensor,              # model input (or a tuple for multiple inputs)
                  "torch_matmul.onnx")             # output file name
help(torch.onnx.export)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0831918505942275, 'fraction_numerical': 0.010752688172043012, 'mean_word_length': 3.830601092896175, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '296223', 'license': 'Apache-2.0', 'n_tokens_mistral': 569, 'n_tokens_neox': 550, 'n_words': 181, 'path': 'site/ai-on-z-samples/onnx-conversion/torch_export_onnx.ipynb', 'repo_name': 'IBM/ai-on-z-101', 'size': '1767'}