Exporting models from CNTK to ONNX

In this tutorial, we will demonstrate how to export a CNTK model to the ONNX format.


To export to ONNX, simply make sure you have CNTK 2.3.1 or higher installed.
Follow CNTK installation instructions here.

API Usage

To save a CNTK model to the ONNX format, specify the ONNX format in the format parameter of the save function.

Using Python API

import cntk as C

x = C.input_variable(<input shape>)
z = create_model(x) #your create model function
z.save(<path of where to save your ONNX model>, format=C.ModelFormat.ONNX)

Exporting in C#

var x = CNTKLib.InputVariable(<specify input variable parameters>);
Function z = CreateModel(x); //your create model function
z.Save(<path of where to save your ONNX model>, ModelFormat.ONNX);

Trying it out with ResNet-20

Let's go through an example of exporting a pretrained CNTK model to ONNX.

Step 1: Prepare a CNTK model to export

For this tutorial, we will be using a pretrained ResNet-20 model (trained on the CIFAR-10 dataset) from the collection of pretrained CNTK models found here. Download the model to your working directory. (Note that not all of the models found here are exportable to the ONNX format yet.)
Download link: https://www.cntk.ai/Models/CNTK_Pretrained/ResNet20_CIFAR10_CNTK.model

Step 2: Load the model into CNTK

In [10]:
import cntk as C
In [11]:
model_path = "ResNet20_CIFAR10_CNTK.model"
z = C.Function.load(model_path, device=C.device.cpu())

Step 3: Export the model to ONNX

Next, export the CNTK model by saving it out to the ONNX format.

In [12]:
z.save("model.onnx", format=C.ModelFormat.ONNX)