Prepare PyTorch Models for MATLAB and Simulink Code Generation
R2026bTo load a PyTorch® model for simulation and code generation in MATLAB® and Simulink®, you must first export the model to a PyTorch ExportedProgram file as a PT2 file in the Python® environment. The ExportedProgram file provides a framework-independent file that represents a PyTorch model. It captures the model’s computation graph, input and output specifications, and parameters in a deterministic structure that MATLAB uses for inference during simulation, and code generation. This page describes the standard process for exporting a PyTorch model.

Export PyTorch Model to PyTorch ExportedProgram file
Prerequisites
To perform the exporting process in the Python environment outside of MATLAB, you must have:
A working installation of Python.
PyTorch version 2.7.1 to version 2.11.
Create the PyTorch Model
Create a Python file that defines your model architecture. For example, create a
file named simple_net.py inside a models directory.
The code below defines a neural network class named simpleNet.
The network contains two linear layers and a ReLU activation function. The
forward method specifies how input data flows through the
network to produce an output.
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 the Python Script to Export the Model
Once you have trained simpleNet in Python, create a file named
exportModel.py to perform the export. This file performs
these steps:
Import the libraries and the
SimpleNetclass.Create an instance of the model and calls
model.eval()to set it to inference mode.Create sample input that matches the expected input size of the model to trace the model's structure.
Use
torch.export.export()function to trace the model and returns a ExportedProgram object namedexported_program. For more information, see https://docs.pytorch.org/docs/stable/export.html.Use
torch.export.save()to serialize the ExportedProgram object and save it to the filesimple_net.pt2.
# 1. Import libraries and classes
import torch
import torch.export
from simple_net import SimpleNet
from torch.export import Dim
# 2. Instantiate the model and set it to evaluation mode
model = SimpleNet()
model.eval()
# 3. Define example inputs for tracing
example_inputs = (torch.randn(2, 10),) # Dynamic dimension cannot have size of 0 or 1 per documentation
# 4. Specify dynamic dimensions
dynamic_dimensions = {
'x': {0: Dim.DYNAMIC} # OR Dim('batch_size') # 'x' is the name of the input, Make its first dimension (batch size) dynamic
}
# 5. Convert the model to ExportedProgram object
exported_program = torch.export.export(model, example_inputs, dynamic_shapes=dynamic_dimensions)
# 6. Save the ExportedProgram to a .pt2 file.
output_path = "simple_net.pt2"
torch.export.save(exported_program, output_path)
Run the Export Script
Execute exportModel.py from your terminal to create a file
named simple_net.pt2.
python exportModel.pyLoad PyTorch ExportedProgram file in MATLAB
Use the loadPyTorchExportedProgram function to load the PyTorch ExportedProgram
file simple_net.pt2 into MATLAB. For more information about the
function, see loadPyTorchExportedProgram. To load PyTorch ExportedProgram file in
Simulink, use the PyTorch
ExportedProgram block.
myModel = loadPyTorchExportedProgram("simple_net.pt2")myModel =
PyTorchExportedProgram contained in simple_net.pt2:
Input Specifications
_________________________________________________
Input Name Size Type
_____ _____ ___________________ ________
1 "in1" "1 x 10" "single"
Output Specifications
____________________________________________________
Output Name Size Type
______ ______ ____________________ ________
1 "out1" "1 x 5" "single"
properties:
ModelPath - Path to the model file
FcnNames - Names of the functions in the model
methods:
invoke - Performs forward inference by invoking a function in the model
inputSpecifications - Returns the input specifications of the model or of a specific function in the model
outputSpecifications - Returns the output specifications of the model or of a specific function in the model
summary - Displays the input and output specifications of the model or of a specific function in the model