Contenido principal

Prepare PyTorch Models for MATLAB and Simulink Code Generation

Since R2026a

To load and generate code for a PyTorch® model in MATLAB® and Simulink®, you must export the model to a PyTorch ExportedProgram file. ExportedProgram files are framework independent and contain the computation graph, input and output specifications, and parameters of the model. The file uses a deterministic structure that MATLAB uses for simulation and code generation. After exporting a model, you can load the PyTorch ExportedProgram file into MATLAB by using the loadPyTorchExportedProgram function. You can also load the file in Simulink by using the PyTorch ExportedProgram block.

diagram that shows overall process of exporting a PyTorch model to a ExportedProgram file, then loading the file into MATLAB and Simulink.

Export PyTorch Model to PyTorch ExportedProgram File

To export a PyTorch model to an ExportedProgram file, you must install the required versions of PyTorch and Python, create a Python script that exports the model, then run the script.

Install Required Software

To export a PyTorch model, you must have:

  • A working installation of Python

  • PyTorch version 2.8.0

Create Python Script

You can load a pretrained PyTorch model directly and proceed to the export step. Alternatively, define your own architecture and train the model. For example, this code defines a neural network class named simpleNet used as a sample model.

import torch
import torch.nn as nn
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer1 = nn.Linear(10, 50)
        self.relu = nn.ReLU()
        self.layer2 = nn.Linear(50, 5)
    def forward(self, x):
        return self.layer2(self.relu(self.layer1(x)))

Create a script to export the file to an ExportedProgram file. This file must perform these steps:

  1. Import the libraries and the class file that defines your model architecture.

  2. Create an instance of the model and set it to inference mode by calling model.eval().

  3. Create a sample input that matches the data the model was trained on. Use the sample input to trace the model and generate a ExportedProgram object by using the torch.export.export() function. For more information, see the torch.export function on the PyTorch website.

  4. Serialize the ExportedProgram object and save it to a PT2 file by using the torch.export.save() function.

Note that code generation does not support loading the ExportedProgram files exported using CUDA tensors. Move both the model parameters and tensor inputs to CPU before exporting the model.

For example, this script exports a neural network class named SimpleNet to an ExportedProgram object named exported_program.

# Import libraries and classes
import torch
import torch.export
from simple_net import SimpleNet

# Instantiate the model and set it to evaluation mode
model = SimpleNet()
model.eval()

# Define example inputs for tracing
example_inputs = (torch.randn(1, 10),)
    
# Convert the model to ExportedProgram object
exported_program = torch.export.export(model, example_inputs)

# Save the ExportedProgram to a PT2 file
output_path = "simple_net.pt2"
torch.export.save(exported_program, output_path)

After you create the script, execute it from your terminal to create the ExportedProgram file. For example, to execute the exportModel.py script, enter:

python exportModel.py

Load PyTorch ExportedProgram File in MATLAB

Use the loadPyTorchExportedProgram function to load the PyTorch ExportedProgram file into MATLAB. For example, to import the simple_net.pt2 file into MATLAB, enter:

myModel = loadPyTorchExportedProgram("simple_net.pt2")

Load PyTorch ExportedProgram File in Simulink

Use the PyTorch ExportedProgram block from the MATLAB Coder Support Package for PyTorch & LiteRT Models library to load the PyTorch ExportedProgram file into Simulink. Specify the name or path of a PyTorch ExportedProgram model file. For an example, see Simulate and Generate Code for Depth Anything V2 PyTorch Model in Simulink. Alternatively, you can load the PyTorch ExportedProgram file in Simulink by using the loadPyTorchExportedProgram function inside a MATLAB Function block.

See Also

Blocks

Functions

Objects

Topics