Deploy the Pretrained Model on Raspberry Pi

Author: Ziheng Jiang, Hiroyuki Makino

This is an example of using Relay to compile a ResNet model and deploy it on Raspberry Pi.

import tvm
import tvm.relay as relay
from tvm import rpc
from tvm.contrib import util, graph_runtime as runtime
from import download_testdata

Build TVM Runtime on Device

The first step is to build the TVM runtime on the remote device.


All instructions in both this section and next section should be executed on the target device, e.g. Raspberry Pi. And we assume it has Linux running.

Since we do compilation on local machine, the remote device is only used for running the generated code. We only need to build tvm runtime on the remote device.

git clone --recursive
cd tvm
mkdir build
cp cmake/config.cmake build
cd build
cmake ..
make runtime -j4

After building runtime successfully, we need to set environment varibles in ~/.bashrc file. We can edit ~/.bashrc using vi ~/.bashrc and add the line below (Assuming your TVM directory is in ~/tvm):

export PYTHONPATH=$PYTHONPATH:~/tvm/python

To update the environment variables, execute source ~/.bashrc.

Set Up RPC Server on Device

To start an RPC server, run the following command on your remote device (Which is Raspberry Pi in our example).

python -m tvm.exec.rpc_server --host --port=9090

If you see the line below, it means the RPC server started successfully on your device.

INFO:root:RPCServer: bind to

Prepare the Pre-trained Model

Back to the host machine, which should have a full TVM installed (with LLVM).

We will use pre-trained model from MXNet Gluon model zoo. You can found more details about this part at tutorial Compile MXNet Models.

from import get_model
from PIL import Image
import numpy as np

# one line to get the model
block = get_model('resnet18_v1', pretrained=True)

In order to test our model, here we download an image of cat and transform its format.

img_url = ''
img_name = 'cat.png'
img_path = download_testdata(img_url, img_name, module='data')
image =, 224))

def transform_image(image):
    image = np.array(image) - np.array([123., 117., 104.])
    image /= np.array([58.395, 57.12, 57.375])
    image = image.transpose((2, 0, 1))
    image = image[np.newaxis, :]
    return image

x = transform_image(image)


File /workspace/.tvm_test_data/data/cat.png exists, skip.

synset is used to transform the label from number of ImageNet class to the word human can understand.

synset_url = ''.join(['',
synset_name = 'imagenet1000_clsid_to_human.txt'
synset_path = download_testdata(synset_url, synset_name, module='data')
with open(synset_path) as f:
    synset = eval(


File /workspace/.tvm_test_data/data/imagenet1000_clsid_to_human.txt exists, skip.

Now we would like to port the Gluon model to a portable computational graph. It’s as easy as several lines.

# We support MXNet static graph(symbol) and HybridBlock in mxnet.gluon
shape_dict = {'data': x.shape}
func, params = relay.frontend.from_mxnet(block, shape_dict)
# we want a probability so add a softmax operator
func = relay.Function(func.params, relay.nn.softmax(func.body), None, func.type_params, func.attrs)

Here are some basic data workload configurations.

batch_size = 1
num_classes = 1000
image_shape = (3, 224, 224)
data_shape = (batch_size,) + image_shape

Compile The Graph

To compile the graph, we call the function with the graph configuration and parameters. However, You cannot to deploy a x86 program on a device with ARM instruction set. It means Relay also needs to know the compilation option of target device, apart from arguments net and params to specify the deep learning workload. Actually, the option matters, different option will lead to very different performance.

If we run the example on our x86 server for demonstration, we can simply set it as llvm. If running it on the Raspberry Pi, we need to specify its instruction set. Set local_demo to False if you want to run this tutorial with a real device.

local_demo = True

if local_demo:
    target ='llvm')
    target ='rasp3b')
    # The above line is a simple form of
    # target ='llvm -device=arm_cpu -model=bcm2837 -target=armv7l-linux-gnueabihf -mattr=+neon')

with relay.build_config(opt_level=3):
    graph, lib, params =, target, params=params)

# After ``, you will get three return values: graph,
# library and the new parameter, since we do some optimization that will
# change the parameters but keep the result of model as the same.

# Save the library at local temporary directory.
tmp = util.tempdir()
lib_fname = tmp.relpath('net.tar')

Deploy the Model Remotely by RPC

With RPC, you can deploy the model remotely from your host machine to the remote device.

# obtain an RPC session from remote device.
if local_demo:
    remote = rpc.LocalSession()
    # The following is my environment, change this to the IP address of your target device
    host = ''
    port = 9090
    remote = rpc.connect(host, port)

# upload the library to remote device and load it
rlib = remote.load_module('net.tar')

# create the remote runtime module
ctx = remote.cpu(0)
module = runtime.create(graph, rlib, ctx)
# set parameter (upload params to the remote device. This may take a while)
# set input data
module.set_input('data', tvm.nd.array(x.astype('float32')))
# run
# get output
out = module.get_output(0)
# get top1 result
top1 = np.argmax(out.asnumpy())
print('TVM prediction top-1: {}'.format(synset[top1]))


TVM prediction top-1: tiger cat

Total running time of the script: ( 0 minutes 14.990 seconds)

Gallery generated by Sphinx-Gallery