Compile CoreML Models

Author: Joshua Z. Zhang

This article is an introductory tutorial to deploy CoreML models with NNVM.

For us to begin with, coremltools module is required to be installed.

A quick solution is to install via pip `bash pip install -U coremltools --user ` or please refer to offical site

import nnvm
import tvm
import coremltools as cm
import numpy as np
from PIL import Image

def download(url, path, overwrite=False):
    import os
    if os.path.isfile(path) and not overwrite:
        print('File {} existed, skip.'.format(path))
    print('Downloading from url {} to {}'.format(url, path))
        import urllib.request
        urllib.request.urlretrieve(url, path)
        import urllib
        urllib.urlretrieve(url, path)

Load pretrained CoreML model

We will download and load a pretrained mobilenet classification network privided by apple in this example

model_url = ''
model_file = 'mobilenet.mlmodel'
download(model_url, model_file)
# now you mobilenet.mlmodel on disk
mlmodel = cm.models.MLModel(model_file)
# we can load the graph as NNVM compatible model
sym, params = nnvm.frontend.from_coreml(mlmodel)


Downloading from url to mobilenet.mlmodel

Load a test image

A single cat dominates the examples!

from PIL import Image
img_url = ''
download(img_url, 'cat.png')
img ='cat.png').resize((224, 224))
x = np.transpose(img, (2, 0, 1))[np.newaxis, :]


Downloading from url to cat.png

Compile the model on NNVM

We should be familiar with the process right now.

import nnvm.compiler
target = 'cuda'
shape_dict = {'image': x.shape}
graph, lib, params =, target, shape_dict, params=params)

Execute on TVM

The process is no different from other example

from tvm.contrib import graph_runtime
ctx = tvm.gpu(0)
dtype = 'float32'
m = graph_runtime.create(graph, lib, ctx)
# set inputs
m.set_input('image', tvm.nd.array(x.astype(dtype)))
# execute
# get outputs
output_shape = (1000,)
tvm_output = m.get_output(0, tvm.nd.empty(output_shape, dtype)).asnumpy()
top1 = np.argmax(tvm_output)

Look up synset name

Look up prdiction top 1 index in 1000 class synset.

synset_url = ''.join(['',
synset_name = 'synset.txt'
download(synset_url, synset_name)
with open(synset_name) as f:
    synset = eval(
print('Top-1 id', top1, 'class name', synset[top1])


File synset.txt existed, skip.
Top-1 id 287 class name lynx, catamount

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

Generated by Sphinx-Gallery