forward
R2026bSyntax
Description
[
passes Y1,...,YN] = forward(model,X1,...,XM)X1,...,XM to Python®, converting any numeric MATLAB® arrays to torch.Tensor objects, and invokes the PyTorch® model on the Python inputs.
forward invokes the model using Python function call syntax, which typically calls the forward()
method of the model. This approach is recommended for performing inference or training with
PyTorch models. The behavior depends on the TrainingMode property
of the model: set it to "eval" for inference or
"train" for training.
[___] = forward(___,
also passes Python keyword arguments to the model invocation command.pyarg1=val1,...,pyargK=valK)
[___] = forward(___,ReturnAsPython=[
specifies which outputs to return as Python types (tf1,...,tfN])py.* objects) rather than converting them to
MATLAB arrays. If you specify ReturnAsPython, it must appear last
in the argument list.
Examples
Input Arguments
Output Arguments
Tips
forwardsupports a fixed number of mandatory positional arguments followed by optional keyword arguments. The number of mandatory positional arguments is set by theNumInputsproperty of the model at construction time. At call time, you must pass exactlyNumInputspositional arguments, followed by any number of keyword arguments.If the underlying Python
forward()method accepts optional or variadic positional arguments, write a separate standalone Python function for each number of positional inputs you need, then useaddFunctionandcallFunctionto call them individually. For example, defineforward_2()that accepts two inputs, add it withaddFunction(model,"myModule.forward_2",NumInputs=2), and call it withcallFunction(model,"myModule.forward_2",X1,X2).Mandatory Python keyword arguments are handled by the optional keyword argument mechanism. If you omit a required keyword argument, Python issues an error at runtime.
Python uses zero-based indexing (the first item in a tensor is at index 0), while MATLAB uses one-based indexing (the first item in an array is at index 1). Ensure that you use zero-based indexing when passing index integers to your model.
Algorithms
Version History
Introduced in R2026b
See Also
Functions
addFunction|callFunction|export|reload|importNetworkFromPyTorch|arrayToTorchTensor|torchTensorToArray
Objects
PyTorchModel|(Parallel Computing Toolbox)gpuArray