{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Importing models from ONNX to Caffe2\n", "\n", "In this tutorial we are going to show you how to import ONNX models to Caffe2. You can either\n", "\n", "- Directly run an ONNX model with Caffe2 in Python\n", "\n", "or\n", "\n", "- Convert an ONNX model file to a Caffe2 model file, and then later run the converted Caffe2 model in any environment that Caffe2 supports, e.g. on mobile phones." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Installation\n", "\n", "`onnx-caffe2` is now integrated as part of `caffe2` under `caffe2/python/onnx`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Run an ONNX model with Caffe2" ] }, { "cell_type": "code", "execution_count": 0, "metadata": {}, "outputs": [], "source": [ "import onnx\n", "import caffe2.python.onnx.backend\n", "\n", "# Prepare the inputs, here we use numpy to generate some random inputs for demo purpose\n", "import numpy as np\n", "img = np.random.randn(1, 3, 224, 224).astype(np.float32)\n", "\n", "# Load the ONNX model\n", "model = onnx.load('assets/squeezenet.onnx')\n", "# Run the ONNX model with Caffe2\n", "outputs = caffe2.python.onnx.backend.run_model(model, [img])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Convert ONNX model file to Caffe2 model file\n", "`onnx-caffe2` has bundled a shell command `convert-onnx-to-caffe2` for converting ONNX model file to Caffe2 model file. \n", "\n", "\n", "```shell\n", "\n", "$ convert-onnx-to-caffe2 assets/squeezenet.onnx --output predict_net.pb --init-net-output init_net.pb\n", "\n", "```\n", "\n", "Note in ONNX model file, parameters and network structure are all stored in one model file, while in Caffe2, they are normally stored in separated `init_net.pb` (parameters) and `predict_net.pb` (network structure) files." ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" } }, "nbformat": 4, "nbformat_minor": 2 }