标签: TVM

TVM上YOLO-DarkNet多图性能对比

TVM上YOLO-DarkNet的部署已经在之前的文章TVM上部署YOLO-DarkNet及单图性能对比中介绍了。在单图测试结果中,TVM的速度提升约为1.27x。测出的时间数据显示,TVM测试代码中的STAGE1,也就是将模型导入Relay、编译模型的阶段是耗时最长的部分,而导入检测图片和执行检测图片的过程耗时较少。于是本文进一步使用多张图片进行测试。

第一部分 不使用TVM运行YOLO-DarkNet

YOLO-DarkNet的环境配置已经在之前的文章中介绍了。
之前讲到,运用YOLO进行单张图片检测的命令是:

./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg

如果要进行多张图片检测的话,需要对程序进行修改,实现批量测试图片并保存在自定义文件夹下,主要修改的是examples目录下的detector.c文件。

第一步,用下面的代码替换detector.c中的test_detector函数,请注意有三处路径需要改成自己的路径:

void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen)
{
    list *options = read_data_cfg(datacfg);
    char *name_list = option_find_str(options, "names", "data/names.list");
    char **names = get_labels(name_list);

    image **alphabet = load_alphabet();
    network *net = load_network(cfgfile, weightfile, 0);
    set_batch_network(net, 1);
    srand(2222222);
    double time;
    char buff[256];
    char *input = buff;
    float nms=.45;
    int i=0;
    while(1){
        if(filename){
            strncpy(input, filename, 256);
            image im = load_image_color(input,0,0);
            image sized = letterbox_image(im, net->w, net->h);
        //image sized = resize_image(im, net->w, net->h);
        //image sized2 = resize_max(im, net->w);
        //image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h);
        //resize_network(net, sized.w, sized.h);
            layer l = net->layers[net->n-1];


            float *X = sized.data;
            time=what_time_is_it_now();
            network_predict(net, X);
            printf("%s: Predicted in %f seconds.\n", input, what_time_is_it_now()-time);
            int nboxes = 0;
            detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes);
            //printf("%d\n", nboxes);
            //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms);
            if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
                draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes);
                free_detections(dets, nboxes);
            if(outfile)
             {
                save_image(im, outfile);
             }
            else{
                save_image(im, "predictions");
#ifdef OPENCV
                cvNamedWindow("predictions", CV_WINDOW_NORMAL); 
                if(fullscreen){
                cvSetWindowProperty("predictions", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
                }
                show_image(im, "predictions");
                cvWaitKey(0);
                cvDestroyAllWindows();
#endif
            }
            free_image(im);
            free_image(sized);
            if (filename) break;
         } 
        else {
            printf("Enter Image Path: ");
            fflush(stdout);
            input = fgets(input, 256, stdin);
            if(!input) return;
            strtok(input, "\n");

            list *plist = get_paths(input);
            char **paths = (char **)list_to_array(plist);
             printf("Start Testing!\n");
            int m = plist->size;
            if(access("/home/ztj/tvm/darknet/data/multi/out",0)==-1)//要改成自己的输出路径
            {
              if (mkdir("/home/ztj/tvm/darknet/data/multi/out",0777))//要改成自己的输出路径
               {
                 printf("creat file bag failed!!!");
               }
            }
            for(i = 0; i < m; ++i){
             char *path = paths[i];
             image im = load_image_color(path,0,0);
             image sized = letterbox_image(im, net->w, net->h);
        //image sized = resize_image(im, net->w, net->h);
        //image sized2 = resize_max(im, net->w);
        //image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h);
        //resize_network(net, sized.w, sized.h);
        layer l = net->layers[net->n-1];


        float *X = sized.data;
        time=what_time_is_it_now();
        network_predict(net, X);
        printf("Try Very Hard:");
        printf("%s: Predicted in %f seconds.\n", path, what_time_is_it_now()-time);
        int nboxes = 0;
        detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes);
        //printf("%d\n", nboxes);
        //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms);
        if (nms) do_nms_sort(dets, nboxes, l.classes, nms);
        draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes);
        free_detections(dets, nboxes);
        if(outfile){
            save_image(im, outfile);
        }
        else{

             char b[2048];
            sprintf(b,"/home/ztj/tvm/darknet/data/multi/out/%s",GetFilename(path));//要改成自己的输出路径

            save_image(im, b);
            printf("save %s successfully!\n",GetFilename(path));
#ifdef OPENCV
            cvNamedWindow("predictions", CV_WINDOW_NORMAL); 
            if(fullscreen){
                cvSetWindowProperty("predictions", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);
            }
            show_image(im, "predictions");
            cvWaitKey(0);
            cvDestroyAllWindows();
#endif
        }

        free_image(im);
        free_image(sized);
        if (filename) break;
        }
      }
    }
}

第二步,在最前面添加*GetFilename(char *p)函数,注意strncpy(name,q,1);中的最后一个参数是图片文件名的长度,要根据实际情况更改。

#include "darknet.h"
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
static int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90};

char *GetFilename(char *p)
{ 
    static char name[20]={""};
    char *q = strrchr(p,'/') + 1;
    strncpy(name,q,1);//此处的1是图片文件名的长度,要根据实际情况更改。
    return name;
}

第三步,在darknet目录下重新make。

第四步,将需要检测的图片路径写在一个txt文件中,例如:

/home/ztj/tvmtt/darknet/0.jpg
/home/ztj/tvmtt/darknet/1.jpg
/home/ztj/tvmtt/darknet/2.jpg
/home/ztj/tvmtt/darknet/3.jpg
/home/ztj/tvmtt/darknet/4.jpg
/home/ztj/tvmtt/darknet/5.jpg
/home/ztj/tvmtt/darknet/6.jpg

第五步,开始批量测试:

./darknet detector test cfg/voc.data cfg/yolov3.cfg yolov3.weights

程序提示输入图片的路径,我们在这里将第四步中的txt文件的路径填入,测试即开始。

第二部分 在TVM上YOLO-DarkNet多图测试

在TVM上部署YOLO-DarkNet的过程已经在之前的文章中介绍了。
要在TVM上进行多图测试,我们需要对之前的测试代码进行修改,主要修改是模型编译完成之后加入循环读入图片的过程,其中有一处路径需要修改成自己的图片输入路径(见注释),文件名以0.jpg 1.jpg这样的格式命名。测试代码如下:

# numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt
import sys

# tvm, relay
import tvm
from tvm import relay
from ctypes import *
from tvm.contrib.download import download_testdata
from tvm.relay.testing.darknet import __darknetffi__
import tvm.relay.testing.yolo_detection
import tvm.relay.testing.darknet

import datetime

# Model name
MODEL_NAME = 'yolov3'

CFG_NAME = MODEL_NAME + '.cfg'
WEIGHTS_NAME = MODEL_NAME + '.weights'
REPO_URL = 'https://github.com/dmlc/web-data/blob/master/darknet/'
CFG_URL = REPO_URL + 'cfg/' + CFG_NAME + '?raw=true'
WEIGHTS_URL = 'https://pjreddie.com/media/files/' + WEIGHTS_NAME

cfg_path = download_testdata(CFG_URL, CFG_NAME, module="darknet")
# cfg_path = "/home/ztj/.tvm_test_data/darknet/yolov3.cfg"

weights_path = download_testdata(WEIGHTS_URL, WEIGHTS_NAME, module="darknet")
# weights_path = "/home/ztj/.tvm_test_data/darknet/yolov3.weights"

# Download and Load darknet library
if sys.platform in ['linux', 'linux2']:
    DARKNET_LIB = 'libdarknet2.0.so'
    DARKNET_URL = REPO_URL + 'lib/' + DARKNET_LIB + '?raw=true'
elif sys.platform == 'darwin':
    DARKNET_LIB = 'libdarknet_mac2.0.so'
    DARKNET_URL = REPO_URL + 'lib_osx/' + DARKNET_LIB + '?raw=true'
else:
    err = "Darknet lib is not supported on {} platform".format(sys.platform)
    raise NotImplementedError(err)

lib_path = download_testdata(DARKNET_URL, DARKNET_LIB, module="darknet")
# lib_path = "/home/ztj/.tvm_test_data/darknet/libdarknet2.0.so"

# ******timepoint1-start*******
start1 = datetime.datetime.now()
# ******timepoint1-start*******

DARKNET_LIB = __darknetffi__.dlopen(lib_path)
net = DARKNET_LIB.load_network(cfg_path.encode('utf-8'), weights_path.encode('utf-8'), 0)
dtype = 'float32'
batch_size = 1

data = np.empty([batch_size, net.c, net.h, net.w], dtype)
shape_dict = {'data': data.shape}
print("Converting darknet to relay functions...")
mod, params = relay.frontend.from_darknet(net, dtype=dtype, shape=data.shape)

######################################################################
# Import the graph to Relay
# -------------------------
# compile the model
target = 'llvm'
target_host = 'llvm'
ctx = tvm.cpu(0)
data = np.empty([batch_size, net.c, net.h, net.w], dtype)
shape = {'data': data.shape}
print("Compiling the model...")
with relay.build_config(opt_level=3):
    graph, lib, params = relay.build(mod,
                                     target=target,
                                     target_host=target_host,
                                     params=params)

[neth, netw] = shape['data'][2:] # Current image shape is 608x608

# ******timepoint1-end*******
end1 = datetime.datetime.now()
# ******timepoint1-end*******

TEST_IMAGE_NUM = 7

coco_name = 'coco.names'
coco_url = REPO_URL + 'data/' + coco_name + '?raw=true'
font_name = 'arial.ttf'
font_url = REPO_URL + 'data/' + font_name + '?raw=true'
coco_path = download_testdata(coco_url, coco_name, module='data')
font_path = download_testdata(font_url, font_name, module='data')
# coco_path = "/home/ztj/.tvm_test_data/data/coco.names"
# font_path = "/home/ztj/.tvm_test_data/data/arial.ttf"

print(end1-start1)

for i in range(0,TEST_IMAGE_NUM):
    # ******timepoint2-start*******
    start2 = datetime.datetime.now()
    # ******timepoint2-start*******
    test_image = str(i) + '.jpg'
    # print("Loading the test image...")
    img_url = REPO_URL + 'data/' + test_image + '?raw=true'
    # img_path = download_testdata(img_url, test_image, "data")
    img_path = "/home/ztj/.tvm_test_data/data/darknet_multi/" + test_image //改成自己的图片路径

    data = tvm.relay.testing.darknet.load_image(img_path, netw, neth)

    from tvm.contrib import graph_runtime

    m = graph_runtime.create(graph, lib, ctx)

    # set inputs
    m.set_input('data', tvm.nd.array(data.astype(dtype)))
    m.set_input(**params)
    # execute
    # print("Running the test image...")

    m.run()
    # get outputs
    tvm_out = []
    if MODEL_NAME == 'yolov2':
        layer_out = {}
        layer_out['type'] = 'Region'
        # Get the region layer attributes (n, out_c, out_h, out_w, classes, coords, background)
        layer_attr = m.get_output(2).asnumpy()
        layer_out['biases'] = m.get_output(1).asnumpy()
        out_shape = (layer_attr[0], layer_attr[1]//layer_attr[0],
                    layer_attr[2], layer_attr[3])
        layer_out['output'] = m.get_output(0).asnumpy().reshape(out_shape)
        layer_out['classes'] = layer_attr[4]
        layer_out['coords'] = layer_attr[5]
        layer_out['background'] = layer_attr[6]
        tvm_out.append(layer_out)

    elif MODEL_NAME == 'yolov3':
        for i in range(3):
            layer_out = {}
            layer_out['type'] = 'Yolo'
            # Get the yolo layer attributes (n, out_c, out_h, out_w, classes, total)
            layer_attr = m.get_output(i*4+3).asnumpy()
            layer_out['biases'] = m.get_output(i*4+2).asnumpy()
            layer_out['mask'] = m.get_output(i*4+1).asnumpy()
            out_shape = (layer_attr[0], layer_attr[1]//layer_attr[0],
                        layer_attr[2], layer_attr[3])
            layer_out['output'] = m.get_output(i*4).asnumpy().reshape(out_shape)
            layer_out['classes'] = layer_attr[4]
            tvm_out.append(layer_out)

    # do the detection and bring up the bounding boxes
    thresh = 0.5
    nms_thresh = 0.45
    img = tvm.relay.testing.darknet.load_image_color(img_path)
    _, im_h, im_w = img.shape
    dets = tvm.relay.testing.yolo_detection.fill_network_boxes((netw, neth), (im_w, im_h), thresh,
                                                        1, tvm_out)
    last_layer = net.layers[net.n - 1]
    tvm.relay.testing.yolo_detection.do_nms_sort(dets, last_layer.classes, nms_thresh)

    with open(coco_path) as f:
        content = f.readlines()

    names = [x.strip() for x in content]
    # print(names)
    tvm.relay.testing.yolo_detection.draw_detections(font_path, img, dets, thresh, names, last_layer.classes)

    # ******timepoint2-end*******
    end2 = datetime.datetime.now()
    # ******timepoint2-end*******
    print(end2-start2)

    # plt.imshow(img.transpose(1, 2, 0))
    plt.imsave(test_image,img.transpose(1, 2, 0))
    # plt.show()

第三部分 运行测试及性能对比

对直接运行及在TVM上运行分别进行十次重复测试,得到以下测试结果:

TVM上部署YOLO-DarkNet及单图性能对比

本文根据TVM官方文档Compile YOLO-V2 and YOLO-V3 in DarkNet Models提供的例程实现了在TVM上部署YOLO-DarkNet,并对使用TVM进行优化的效果进行了性能测试及对比。本文以YOLO-V3为例。
操作系统:Ubuntu 18.04
Backend:虚拟机 CPU

第一部分 不使用TVM运行YOLO-DarkNet

YOLO-DarkNet安装

从GitHub上将DarkNet clone下来

git clone https://github.com/pjreddie/darknet.git
cd darknet
make

make完毕后,运行

./darknet

如出现以下提示,则安装成功:

TIM截图20190706162940

为了测试YOLO,我们需要下载官方训练好的权重文件yolov3.weights,下载地址为https://pjreddie.com/media/files/yolov3.weights

官网的下载速度较慢,可以提前至可信的国内平台下载。weights文件放在darknet目录下。

运行YOLO进行图像检测

运行以下命令:

./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg

可看到以下效果:

TIM截图20190706163835

检测结果保存在predictions.jpg中:

predictions

由于我们是在CPU上运行YOLO,且虚拟机CPU性能并不是很强,本次检测耗时32.126040s。

接下来我们在TVM上实现相同的效果并测试时间。

第二部分 在TVM上部署YOLO-DarkNet

这一部分的示例代码来自官方文档Compile YOLO-V2 and YOLO-V3 in DarkNet Models,为了对性能进行测试,我向其中加入了计时代码。

运行测试程序之前,需要先对环境进行配置,安装CFFI和CV2:

pip install cffi
pip install opencv-python

环境配置完成后即可运行检测程序。
TVM的官方示例代码中使用download_testdata函数从网络下载所需文件并返回目录,此处因为weights文件官网下载速度过慢,所以建议提前下载并放置在用户目录下的/.tvm_test_data/darknet/目录中。为了防止偶现的由于网络问题导致download_testdata函数执行出错而中断程序,当所有所需文件下载完成后,可直接填写文件的路径变量,提高运行效率。
为了防止下载、加载文件等操作影响对程序运行时间计算的干扰,我们将程序分为三部分计时。

# 导入 numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt
import sys

# 导入 tvm, relay
import tvm
from tvm import relay
from ctypes import *
from tvm.contrib.download import download_testdata
from tvm.relay.testing.darknet import __darknetffi__
import tvm.relay.testing.yolo_detection
import tvm.relay.testing.darknet

import datetime

# 设置 Model name
MODEL_NAME = 'yolov3'

######################################################################
# 下载所需文件
# -----------------------
# 这部分程序下载cfg及weights文件。
CFG_NAME = MODEL_NAME + '.cfg'
WEIGHTS_NAME = MODEL_NAME + '.weights'
REPO_URL = 'https://github.com/dmlc/web-data/blob/master/darknet/'
CFG_URL = REPO_URL + 'cfg/' + CFG_NAME + '?raw=true'
WEIGHTS_URL = 'https://pjreddie.com/media/files/' + WEIGHTS_NAME

cfg_path = download_testdata(CFG_URL, CFG_NAME, module="darknet")
# 以下为直接填写路径值示例,后同。
# cfg_path = "/home/ztj/.tvm_test_data/darknet/yolov3.cfg"

weights_path = download_testdata(WEIGHTS_URL, WEIGHTS_NAME, module="darknet")
# weights_path = "/home/ztj/.tvm_test_data/darknet/yolov3.weights"

# 下载并加载DarkNet Library
if sys.platform in ['linux', 'linux2']:
    DARKNET_LIB = 'libdarknet2.0.so'
    DARKNET_URL = REPO_URL + 'lib/' + DARKNET_LIB + '?raw=true'
elif sys.platform == 'darwin':
    DARKNET_LIB = 'libdarknet_mac2.0.so'
    DARKNET_URL = REPO_URL + 'lib_osx/' + DARKNET_LIB + '?raw=true'
else:
    err = "Darknet lib is not supported on {} platform".format(sys.platform)
    raise NotImplementedError(err)

lib_path = download_testdata(DARKNET_URL, DARKNET_LIB, module="darknet")
# lib_path = "/home/ztj/.tvm_test_data/darknet/libdarknet2.0.so"

# ******timepoint1-start*******
start1 = datetime.datetime.now()
# ******timepoint1-start*******

DARKNET_LIB = __darknetffi__.dlopen(lib_path)
net = DARKNET_LIB.load_network(cfg_path.encode('utf-8'), weights_path.encode('utf-8'), 0)
dtype = 'float32'
batch_size = 1

data = np.empty([batch_size, net.c, net.h, net.w], dtype)
shape_dict = {'data': data.shape}
print("Converting darknet to relay functions...")
mod, params = relay.frontend.from_darknet(net, dtype=dtype, shape=data.shape)

######################################################################
# 将图导入Relay
# -------------------------
# 编译模型
target = 'llvm'
target_host = 'llvm'
ctx = tvm.cpu(0)
data = np.empty([batch_size, net.c, net.h, net.w], dtype)
shape = {'data': data.shape}
print("Compiling the model...")
with relay.build_config(opt_level=3):
    graph, lib, params = relay.build(mod,
                                     target=target,
                                     target_host=target_host,
                                     params=params)

[neth, netw] = shape['data'][2:] # Current image shape is 608x608

# ******timepoint1-end*******
end1 = datetime.datetime.now()
# ******timepoint1-end*******

######################################################################
# 加载测试图片
# -----------------
test_image = 'dog.jpg'
print("Loading the test image...")
img_url = REPO_URL + 'data/' + test_image + '?raw=true'
# img_path = download_testdata(img_url, test_image, "data")
img_path = "/home/ztj/.tvm_test_data/data/dog.jpg"

# ******timepoint2-start*******
start2 = datetime.datetime.now()
# ******timepoint2-start*******

data = tvm.relay.testing.darknet.load_image(img_path, netw, neth)
######################################################################
# 在TVM上执行
# ----------------------
# 过程与其他示例没有差别
from tvm.contrib import graph_runtime

m = graph_runtime.create(graph, lib, ctx)

# 设置输入
m.set_input('data', tvm.nd.array(data.astype(dtype)))
m.set_input(**params)
# 执行
print("Running the test image...")

m.run()
# 获得输出
tvm_out = []
if MODEL_NAME == 'yolov2':
    layer_out = {}
    layer_out['type'] = 'Region'
    # Get the region layer attributes (n, out_c, out_h, out_w, classes, coords, background)
    layer_attr = m.get_output(2).asnumpy()
    layer_out['biases'] = m.get_output(1).asnumpy()
    out_shape = (layer_attr[0], layer_attr[1]//layer_attr[0],
                 layer_attr[2], layer_attr[3])
    layer_out['output'] = m.get_output(0).asnumpy().reshape(out_shape)
    layer_out['classes'] = layer_attr[4]
    layer_out['coords'] = layer_attr[5]
    layer_out['background'] = layer_attr[6]
    tvm_out.append(layer_out)

elif MODEL_NAME == 'yolov3':
    for i in range(3):
        layer_out = {}
        layer_out['type'] = 'Yolo'
        # 获取YOLO层属性 (n, out_c, out_h, out_w, classes, total)
        layer_attr = m.get_output(i*4+3).asnumpy()
        layer_out['biases'] = m.get_output(i*4+2).asnumpy()
        layer_out['mask'] = m.get_output(i*4+1).asnumpy()
        out_shape = (layer_attr[0], layer_attr[1]//layer_attr[0],
                     layer_attr[2], layer_attr[3])
        layer_out['output'] = m.get_output(i*4).asnumpy().reshape(out_shape)
        layer_out['classes'] = layer_attr[4]
        tvm_out.append(layer_out)

# 检测,并进行框选标记。
thresh = 0.5
nms_thresh = 0.45
img = tvm.relay.testing.darknet.load_image_color(img_path)
_, im_h, im_w = img.shape
dets = tvm.relay.testing.yolo_detection.fill_network_boxes((netw, neth), (im_w, im_h), thresh,
                                                      1, tvm_out)
last_layer = net.layers[net.n - 1]
tvm.relay.testing.yolo_detection.do_nms_sort(dets, last_layer.classes, nms_thresh)

# ******timepoint2-end*******
end2 = datetime.datetime.now()
# ******timepoint2-end*******

coco_name = 'coco.names'
coco_url = REPO_URL + 'data/' + coco_name + '?raw=true'
font_name = 'arial.ttf'
font_url = REPO_URL + 'data/' + font_name + '?raw=true'
coco_path = download_testdata(coco_url, coco_name, module='data')
font_path = download_testdata(font_url, font_name, module='data')
# coco_path = "/home/ztj/.tvm_test_data/data/coco.names"
# font_path = "/home/ztj/.tvm_test_data/data/arial.ttf"
# ******timepoint3-start*******
start3 = datetime.datetime.now()
# ******timepoint3-start*******

with open(coco_path) as f:
    content = f.readlines()

names = [x.strip() for x in content]

tvm.relay.testing.yolo_detection.draw_detections(font_path, img, dets, thresh, names, last_layer.classes)
# ******timepoint3-end*******
end3 = datetime.datetime.now()
# ******timepoint3-end*******

print(end1-start1)
print(end2-start2)
print(end3-start3)

plt.imshow(img.transpose(1, 2, 0))
plt.show()

运行程序得到以下结果:

TIM截图20190706171557

相加即得总运行时长。

第三部分 性能对比

对直接运行及在TVM上运行分别进行十次重复测试,得到以下测试结果:

本次测试中,直接运行平均时长为28.196s,TVM上运行平均时长为22.266s,平均提速1.27x。目前还没有在其他硬件平台上进行测试。

在单图测试结果中,TVM的速度提升约为1.27x,测出的时间数据显示,TVM测试代码中的STAGE1,也就是将模型导入Relay、编译模型的阶段是耗时最长的部分,而导入检测图片和执行检测图片的过程耗时较少。接下来将进一步使用多张图片进行测试,文章链接:TVM上YOLO-DarkNet多图性能对比

TVM部署TensorFlow模型

本文是对TVM官方关于如何使用TVM编译TensorFlow模型文档的翻译整理,并记录了实现时遇到的小坑。

TVM部署TensorFlow模型

本文介绍如何使用TVM部署TensorFlow模型。
在开始之前,首先需要安装TensorFlow的Python包。

Python及TensorFlow环境

以下例程需要Python3.5以上的环境才能运行,请使用3.5以上Python的版本。
我在使用Python3.6.5与TensorFlow1.14.0运行例程时遇到如下报错:

Traceback (most recent call last):
  File "from_tensorflow.py", line 129, in <module>
    shape=shape_dict)
  File "/home/USER/local/tvm/python/tvm/relay/frontend/tensorflow.py", line 2413, in from_tensorflow
    mod, params = g.from_tensorflow(graph, layout, shape, outputs)
  File "/home/USER/local/tvm/python/tvm/relay/frontend/tensorflow.py", line 2058, in from_tensorflow
    op = self._convert_operator(node.op, inputs, attr, graph)
  File "/home/USER/local/tvm/python/tvm/relay/frontend/tensorflow.py", line 2376, in _convert_operator
    sym = convert_map[op_name](inputs, attrs, self._params)
  File "/home/USER/local/tvm/python/tvm/relay/frontend/tensorflow.py", line 562, in _impl
    extras={'method': "BILINEAR"})(inputs, attr)
  File "/home/USER/local/tvm/python/tvm/relay/frontend/tensorflow.py", line 155, in __call__
    return _get_relay_op(op_name)(*inputs, **new_attrs)
TypeError: resize() got an unexpected keyword argument 'half_pixel_centers'

回退TensorFlow版本至1.12.0后报错消失。TVM社区关于本问题的探讨:https://discuss.tvm.ai/t/typeerror-when-running-the-from-tensorflow-example/3046

关于TensorFlow的安装请参考https://www.tensorflow.org/install
此处通过pip进行安装即可:

pip3 install TensorFlow==1.12.0
# 导入 tvm, relay  
import tvm  
from tvm import relay  

# 导入 os and numpy  
import numpy as np  
import os.path  

# 导入 Tensorflow imports  
import tensorflow as tf  

# Tensorflow 效用函数
import tvm.relay.testing.tf as tf_testing  

# 相关文件的在线地址(此处使用了dmlc在GitHub上的数据)  
repo_base = 'https://github.com/dmlc/web-data/raw/master/tensorflow/models/InceptionV1/'  

# 测试用图  
img_name = 'elephant-299.jpg'  
image_url = os.path.join(repo_base, img_name)  

教程

有关TensorFlow的各种模型的更多详细信息,请参阅 docs/frontend/tensorflow.md 。

model_name = 'classify_image_graph_def-with_shapes.pb'  
model_url = os.path.join(repo_base, model_name)  

# 图像标签  
map_proto = 'imagenet_2012_challenge_label_map_proto.pbtxt'  
map_proto_url = os.path.join(repo_base, map_proto)  

# 可读的图像标签  
label_map = 'imagenet_synset_to_human_label_map.txt'  
label_map_url = os.path.join(repo_base, label_map)  

# 目标设置  
# 如果使用cuda,可以使用以下推荐配置。  
#target = 'cuda'  
#target_host = 'llvm'  
#layout = "NCHW"  
#ctx = tvm.gpu(0)  
target = 'llvm'  
target_host = 'llvm'  
layout = None  
ctx = tvm.cpu(0)  

下载所需文件

下列程序将下载上面所列的所需文件

from tvm.contrib.download import download_testdata  

img_path = download_testdata(image_url, img_name, module='data')  
model_path = download_testdata(model_url, model_name, module=['tf', 'InceptionV1'])  
map_proto_path = download_testdata(map_proto_url, map_proto, module='data')  
label_path = download_testdata(label_map_url, label_map, module='data')  

导入模型

从protobuf文件创建TensorFlow图定义

with tf.gfile.FastGFile(model_path, 'rb') as f:  
    graph_def = tf.GraphDef()  
    graph_def.ParseFromString(f.read())  
    graph = tf.import_graph_def(graph_def, name='')  
    # 调用效用函数,将图定义导入默认图。  
    graph_def = tf_testing.ProcessGraphDefParam(graph_def)  
    # 向图增加shape。  
    with tf.Session() as sess:  
        graph_def = tf_testing.AddShapesToGraphDef(sess, 'softmax')  

图像解码

官方注解

TensorFlow前端导入不支持JpegDecode等处理操作,所以我们绕过JpegDecode(只返回源节点)。因此,我们需要向TVM提供已解码的帧。

from PIL import Image  
image = Image.open(img_path).resize((299, 299))  

x = np.array(image)  

向Relay导入图

向Relay前端导入TensorFlow图定义。

运行结果:
sym: relay expr for given tensorflow protobuf. params: params
converted from tensorflow params (tensor protobuf).
shape_dict = {'DecodeJpeg/contents': x.shape}  
dtype_dict = {'DecodeJpeg/contents': 'uint8'}  
mod, params = relay.frontend.from_tensorflow(graph_def,  
                                             layout=layout,  
                                             shape=shape_dict)  

print("Tensorflow protobuf imported to relay frontend.")  

构建Relay

根据给定的输入规范,将图送向LLVM目标编译。

运行结果:
graph: Final graph after compilation. params: final params after
compilation. lib: target library which can be deployed on target
with TVM runtime.
with relay.build_config(opt_level=3):  
    graph, lib, params = relay.build(mod,  
                                     target=target,  
                                     target_host=target_host,  
                                     params=params)  

在TVM上执行编译完成的模型

现在我们可以在目标上部署已编译的模型了。

from tvm.contrib import graph_runtime  
dtype = 'uint8'  
m = graph_runtime.create(graph, lib, ctx)  
# 设置输入  
m.set_input('DecodeJpeg/contents', tvm.nd.array(x.astype(dtype)))  
m.set_input(**params)  
# 执行  
m.run()  
# 获得输出  
tvm_output = m.get_output(0, tvm.nd.empty(((1, 1008)), 'float32'))  

处理输出结果

处理模型的输出使之可读。

predictions = tvm_output.asnumpy()  
predictions = np.squeeze(predictions)  

# 创建节点ID-->英文字符串查找表。  
node_lookup = tf_testing.NodeLookup(label_lookup_path=map_proto_path,  
                                    uid_lookup_path=label_path)  

# 打印前五个预测结果  
top_k = predictions.argsort()[-5:][::-1]  
for node_id in top_k:  
    human_string = node_lookup.id_to_string(node_id)  
    score = predictions[node_id]  
    print('%s (score = %.5f)' % (human_string, score))  

TensorFlow运行结果

在TensorFlow上运行相应模型。

def create_graph():  
    """Creates a graph from saved GraphDef file and returns a saver."""  
    # 从已保存的 graph_def.pb 中生成图.  
    with tf.gfile.FastGFile(model_path, 'rb') as f:  
        graph_def = tf.GraphDef()  
        graph_def.ParseFromString(f.read())  
        graph = tf.import_graph_def(graph_def, name='')  
        # 调用效用函数,将图定义导入默认图。  
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)  

def run_inference_on_image(image):  
    """Runs inference on an image.  

    Parameters  
    ----------  
    image: String  
        Image file name.  

    Returns  
    -------  
        Nothing  
    """  
    if not tf.gfile.Exists(image):  
        tf.logging.fatal('File does not exist %s', image)  
    image_data = tf.gfile.FastGFile(image, 'rb').read()  

    # 从已保存的 GraphDef 中创建图  
    create_graph()  

    with tf.Session() as sess:  
        softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')  
        predictions = sess.run(softmax_tensor,  
                               {'DecodeJpeg/contents:0': image_data})  

        predictions = np.squeeze(predictions)  

        # 创建节点ID-->英文字符串查找表。  
        node_lookup = tf_testing.NodeLookup(label_lookup_path=map_proto_path,  
                                            uid_lookup_path=label_path)  

        # 打印前五个预测结果  
        top_k = predictions.argsort()[-5:][::-1]  
        print ("===== TENSORFLOW RESULTS =======")  
        for node_id in top_k:  
            human_string = node_lookup.id_to_string(node_id)  
            score = predictions[node_id]  
            print('%s (score = %.5f)' % (human_string, score))  

run_inference_on_image(img_path)  

完整代码

以下为完整代码:
建议直接在官方文档页面底部下载完整Python源代码及Jupyter notebook:https://docs.tvm.ai/tutorials/frontend/from_tensorflow.html#sphx-glr-download-tutorials-frontend-from-tensorflow-py

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Compile Tensorflow Models
=========================
This article is an introductory tutorial to deploy tensorflow models with TVM.

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

Please refer to https://www.tensorflow.org/install
"""

# tvm, relay
import tvm
from tvm import relay

# os and numpy
import numpy as np
import os.path

# Tensorflow imports
import tensorflow as tf

# Tensorflow utility functions
import tvm.relay.testing.tf as tf_testing

# Base location for model related files.
repo_base = 'https://github.com/dmlc/web-data/raw/master/tensorflow/models/InceptionV1/'

# Test image
img_name = 'elephant-299.jpg'
image_url = os.path.join(repo_base, img_name)

######################################################################
# Tutorials
# ---------
# Please refer docs/frontend/tensorflow.md for more details for various models
# from tensorflow.

model_name = 'classify_image_graph_def-with_shapes.pb'
model_url = os.path.join(repo_base, model_name)

# Image label map
map_proto = 'imagenet_2012_challenge_label_map_proto.pbtxt'
map_proto_url = os.path.join(repo_base, map_proto)

# Human readable text for labels
label_map = 'imagenet_synset_to_human_label_map.txt'
label_map_url = os.path.join(repo_base, label_map)

# Target settings
# Use these commented settings to build for cuda.
#target = 'cuda'
#target_host = 'llvm'
#layout = "NCHW"
#ctx = tvm.gpu(0)
target = 'llvm'
target_host = 'llvm'
layout = None
ctx = tvm.cpu(0)

######################################################################
# Download required files
# -----------------------
# Download files listed above.
from tvm.contrib.download import download_testdata

img_path = download_testdata(image_url, img_name, module='data')
model_path = download_testdata(model_url, model_name, module=['tf', 'InceptionV1'])
map_proto_path = download_testdata(map_proto_url, map_proto, module='data')
label_path = download_testdata(label_map_url, label_map, module='data')

######################################################################
# Import model
# ------------
# Creates tensorflow graph definition from protobuf file.

with tf.gfile.FastGFile(model_path, 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    graph = tf.import_graph_def(graph_def, name='')
    # Call the utility to import the graph definition into default graph.
    graph_def = tf_testing.ProcessGraphDefParam(graph_def)
    # Add shapes to the graph.
    with tf.Session() as sess:
        graph_def = tf_testing.AddShapesToGraphDef(sess, 'softmax')

######################################################################
# Decode image
# ------------
# .. note::
#
#   tensorflow frontend import doesn't support preprocessing ops like JpegDecode.
#   JpegDecode is bypassed (just return source node).
#   Hence we supply decoded frame to TVM instead.
#

from PIL import Image
image = Image.open(img_path).resize((299, 299))

x = np.array(image)

######################################################################
# Import the graph to Relay
# -------------------------
# Import tensorflow graph definition to relay frontend.
#
# Results:
#   sym: relay expr for given tensorflow protobuf.
#   params: params converted from tensorflow params (tensor protobuf).
shape_dict = {'DecodeJpeg/contents': x.shape}
dtype_dict = {'DecodeJpeg/contents': 'uint8'}
mod, params = relay.frontend.from_tensorflow(graph_def,
                                             layout=layout,
                                             shape=shape_dict)

print("Tensorflow protobuf imported to relay frontend.")
######################################################################
# Relay Build
# -----------
# Compile the graph to llvm target with given input specification.
#
# Results:
#   graph: Final graph after compilation.
#   params: final params after compilation.
#   lib: target library which can be deployed on target with TVM runtime.

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

######################################################################
# Execute the portable graph on TVM
# ---------------------------------
# Now we can try deploying the compiled model on target.

from tvm.contrib import graph_runtime
dtype = 'uint8'
m = graph_runtime.create(graph, lib, ctx)
# set inputs
m.set_input('DecodeJpeg/contents', tvm.nd.array(x.astype(dtype)))
m.set_input(**params)
# execute
m.run()
# get outputs
tvm_output = m.get_output(0, tvm.nd.empty(((1, 1008)), 'float32'))

######################################################################
# Process the output
# ------------------
# Process the model output to human readable text for InceptionV1.
predictions = tvm_output.asnumpy()
predictions = np.squeeze(predictions)

# Creates node ID --> English string lookup.
node_lookup = tf_testing.NodeLookup(label_lookup_path=map_proto_path,
                                    uid_lookup_path=label_path)

# Print top 5 predictions from TVM output.
top_k = predictions.argsort()[-5:][::-1]
for node_id in top_k:
    human_string = node_lookup.id_to_string(node_id)
    score = predictions[node_id]
    print('%s (score = %.5f)' % (human_string, score))

######################################################################
# Inference on tensorflow
# -----------------------
# Run the corresponding model on tensorflow

def create_graph():
    """Creates a graph from saved GraphDef file and returns a saver."""
    # Creates graph from saved graph_def.pb.
    with tf.gfile.FastGFile(model_path, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        graph = tf.import_graph_def(graph_def, name='')
        # Call the utility to import the graph definition into default graph.
        graph_def = tf_testing.ProcessGraphDefParam(graph_def)

def run_inference_on_image(image):
    """Runs inference on an image.

    Parameters
    ----------
    image: String
        Image file name.

    Returns
    -------
        Nothing
    """
    if not tf.gfile.Exists(image):
        tf.logging.fatal('File does not exist %s', image)
    image_data = tf.gfile.FastGFile(image, 'rb').read()

    # Creates graph from saved GraphDef.
    create_graph()

    with tf.Session() as sess:
        softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
        predictions = sess.run(softmax_tensor,
                               {'DecodeJpeg/contents:0': image_data})

        predictions = np.squeeze(predictions)

        # Creates node ID --> English string lookup.
        node_lookup = tf_testing.NodeLookup(label_lookup_path=map_proto_path,
                                            uid_lookup_path=label_path)

        # Print top 5 predictions from tensorflow.
        top_k = predictions.argsort()[-5:][::-1]
        print ("===== TENSORFLOW RESULTS =======")
        for node_id in top_k:
            human_string = node_lookup.id_to_string(node_id)
            score = predictions[node_id]
            print('%s (score = %.5f)' % (human_string, score))

run_inference_on_image(img_path)

Ubuntu下TVM的编译安装

官方安装文档地址:https://docs.tvm.ai/install/index.html
系统环境:Ubuntu 18.04 LTS 64-bit,其他环境或需求可参考官方文档。

TVM编译安装

LLVM部分

虽然LLVM对于TVM是可选项,但是如果要部署到CPU端,那么LLVM几乎是必须的,所以建议安装LLVM。本次安装LLVM6.0。
第一步,添加相关源
编辑/etc/apt/sources.list,将以下源加入:

deb http://apt.llvm.org/xenial/ llvm-toolchain-xenial-6.0 main
deb-src http://apt.llvm.org/xenial/ llvm-toolchain-xenial-6.0 main     

加入完成后需取得数字证书

wget -O - http://llvm.org/apt/llvm-snapshot.gpg.key|sudo apt-key add -

然后务必进行apt-get update
第二步,安装LLVM

apt-get install clang-6.0 lldb-6.0

其他操作系统和LLVM版本参考:https://apt.llvm.org/

TVM部分

第一步,从GitHub克隆TVM的repo

git clone --recursive https://github.com/dmlc/tvm

注意此处的--recursive是必须的,否则在编译时会出错。
第二步,安装前准备

sudo apt-get update
sudo apt-get install -y python python-dev python-setuptools gcc libtinfo-dev zlib1g-dev build-essential cmake

第三步,修改config.cmake配置
建立build文件夹,复制config.cmake

mkdir build
cp cmake/config.cmake build

然后修改LLVM配置,将set(USE_LLVM OFF)改为set(USE_LLVM ON)
第四步,启动编译

cd build
cmake ..
make -j4

如果顺利完成,即可进入Python包安装

Python包安装

此处使用官方文档推荐的第一种方法进行Python包安装。这种方法可以使我们更改源代码并重新编译后,无需对Python端进行任何更改。
第一步,编辑~/.bashrc,在文件末尾添加:

export TVM_HOME=/path/to/tvm
export PYTHONPATH=TVM_HOME/python:TVM_HOME/topi/python:TVM_HOME/nnvm/python:{PYTHONPATH}

其中/path/to/tvm为tvm目录。
第二步,使修改立即生效

source ~/.bashrc

最后安装其他Python依赖
必须的依赖:

pip install --user numpy decorator attrs

如果需要RPC Tracker:

pip install --user tornado

如果需要auto-tuning模块:

pip install --user tornado psutil xgboost

解析Relay text format程序必须使用Python 3并安装:

pip install --user mypy orderedset antlr4-python3-runtime