#!/usr/bin/env python # coding: utf-8 # # Exporting model from PyTorch to ONNX # # In this tutorial, we describe how to use ONNX to convert a model defined # in PyTorch into the ONNX format. # # ONNX exporter is part of the [PyTorch repository](http://pytorch.org/docs/master/onnx.html). # # For working with this tutorial, you will need to install [onnx](https://github.com/onnx/onnx). You can get binary builds of onnx with # ``conda install -c conda-forge onnx``. # # ``NOTE``: ONNX is under active development so for the best support consider building PyTorch master branch which can be installed by following # [the instructions here](https://github.com/pytorch/pytorch#from-source) # ## Invoking exporter # # Pretty much it's a matter of replacing `my_model(input)` with `torch.onnx.export(my_model, input, "my_model.onnx")` in your script. # # ### Limitations # # The ONNX exporter is a trace-based exporter, which means that it operates by executing your model once, and exporting the operators which were actually run during this run. This means that if your model is dynamic, e.g., changes behavior depending on input data, the export won’t be accurate. # # Similarly, a trace is might be valid only for a specific input size (which is one reason why we require explicit inputs on tracing). Most of the operators export size-agnostic versions and should work on different batch sizes or input sizes. We recommend examining the model trace and making sure the traced operators look reasonable. # In[1]: import torch.onnx help(torch.onnx.export) # ## Trying it out on AlexNet # # If you already have your model built, it's just a few lines: # In[2]: import torch.onnx import torchvision # Standard ImageNet input - 3 channels, 224x224, # values don't matter as we care about network structure. # But they can also be real inputs. dummy_input = torch.randn(1, 3, 224, 224) # Obtain your model, it can be also constructed in your script explicitly model = torchvision.models.alexnet(pretrained=True) # Invoke export torch.onnx.export(model, dummy_input, "alexnet.onnx") # **That's it!** # # ## Inspecting model # # You can also use ONNX tooling to check the validity of the resulting model or inspect the details # In[3]: import onnx # Load the ONNX model model = onnx.load("alexnet.onnx") # Check that the IR is well formed onnx.checker.check_model(model) # Print a human readable representation of the graph print(onnx.helper.printable_graph(model.graph)) # Notice that all parameters are listed as graph's inputs but they also have stored values initialized in `model.graph.initializers`. # In[ ]: ## What's next Check [PyTorch documentation on onnx file](http://pytorch.org/docs/master/onnx.html) Take a look at [other tutorials, including importing of ONNX models to other frameworks](https://github.com/onnx/tutorials/tree/master/tutorials)