Install dependencies
Key considerations
There are some key elements to understand when converting a NeuralForecast model to ONNX. It comes from our the library works and it explains why directlyto_onnx() doesn’t work.
- The
forwardmethod inneuralforecasttakes a dictionary (windows_batch), but that cannot be traced, so usingto_onnx()directly fails. We must define a wrapper that takes tensors and rebuilds the dictionary internally. - Recall that
futr_exogspans the history and the forecast horizon. When running inference, make sure to pass values that cover the input window and the horizon - The series order matters and it must match the order of training.
Internally, series are sorted by
unique_id. At the inference, the same order must be passed. - The scaler matters. With
scaler_type="identity", the output is in the same scale of the series. Any other scaler requires you to inverse-transform the predictions manually. - The batch size used when exporting to ONNX becomes fixed and you
must use the same batch size at inference. To keep it flexible, we
can use
torch.onnx.export(..., dynamo=True). - For multivariate models,
n_seriesmust be constant between training and inference. We set batch size to 1 because predictions are done in one joint window.
Converting a univariate model
Let’s see an example of converting the univariate MLP to ONNX.Import packages
Set constants
Function to create synthetic data
Step1: Create an ONNX wrapper
Step 2: Train the model in neuralforecast
Step 3: Convert to ONNX
Step 4: Prepare input for inference
Step 5: Predict
Converting a multivariate model
Now, let’s see an example of converting the multivariate MLP to ONNX. Note that we don’t repeat the steps to create the synthetic dataset.Step 1: Create the ONNX wrapper
Step 2: Train the model
Step 3: Convert to ONNX
Recall that all series are predicted in one joint window, so batch size is set to 1. Also,n_series is fixed by the trained model.

