Skip to main content
It is possible to convert any NeuralForecast model to the Open Neural Network Exchange (ONNX) format. With ONNX, you get: - faster inference - hardware acceleration - easy deployment to edge devices - a broader device support In this tutorial, we show how you can convert a NeuralForecast model to ONNX. We show an example for a univariate and multivariate model using all types of exogenous features, and with multiple unique series, making it the most general case possible. You can run these experiments using GPU with Google Colab. Open In Colab

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 directly to_onnx() doesn’t work.
  1. The forward method in neuralforecast takes a dictionary (windows_batch), but that cannot be traced, so using to_onnx() directly fails. We must define a wrapper that takes tensors and rebuilds the dictionary internally.
  2. Recall that futr_exog spans the history and the forecast horizon. When running inference, make sure to pass values that cover the input window and the horizon
  3. 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.
  4. 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.
  5. 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).
  6. For multivariate models, n_series must 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.

Step 4: Prepare input for inference

Step 5: Predict