标签: 机器学习

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上运行分别进行十次重复测试,得到以下测试结果:

深度学习(图像方向)常见名词术语

本文是对由邵天兰主讲的知乎Live 深度学习中的常见名词术语(图像方向) 的笔记整理。本文使用到了来自Live Slides以及互联网的一些图片,如有侵权将第一时间删除。

大纲

从分类器开始

图像分类

本节名词列表:
分类(classify)
分类器(classifier)
MNIST
CIFAR10
ImageNet
类内方差(intra-class variance)
类间方差(inter-class variance)
函数(function)
拟合(fit)
数据驱动(data-driven)

分类(classify)

深度学习在图像方向上应用最基本的问题就是分类问题:我们给计算机看一个图像,希望它告诉我们图像里是什么。

分类器(classifier)

为了解决分类问题,我们希望能够做出分类器,而在今天,我们希望通过机器学习的手段做出分类器。

MNIST

MNIST是一个手写数字图片数据集,包含60000张训练样本和10000张测试样本。

1562694139482

CIFAR10

Cifar-10由10个分类的60000张32*32的RGB彩色图片构成,包含50000张训练样本,10000张测试(交叉验证)样本。

1562694141820

ImageNet

ImageNet项目是一个用于视觉对象识别软件研究的大型可视化数据库。提供了标注完成的超过1400万的图像,其中至少一百万个图像还提供了边界框。ImageNet包含2万多个类别。

1562694143576

为了考察分类问题的难易程度,我们来看类内方差与类间方差。

类内方差(intra-class variance)

类内方差是指同一类物体之间的差异,类内方差越大,分类难度越大。例如上面的MNIST数据集中的所有“0”,虽然形态各异,但是差异较小,而上面Cifar-10数据集中的所有“猫”,因为品种、毛色等等方面的区别,就体现出较大的类内差异。显然后者较前者的类内方差更大,完成后者的分类的难度要高于前者。

类间方差(inter-class variance)

类间方差指的是不同类物体之间的差异,类间方差越大,分类难度越低。例如,区分“猫”和“房子”要比取分“猫”和“狗”要容易的多。

函数(function)

分类问题可以理解为让计算机解决类似于由“手写数字8的图片”到“标签8”的映射问题,而我们需要找出的就是完成这一映射的函数。

拟合(fit)

找到这个“函数”的过程我们通常称为拟合出这个函数。

数据驱动(data-driven)

让机器从数据中发现规则、规律,拟合出我们想要的函数,从而解决分类问题,而非使用手动的规则。

分类器入门

本节名词列表
特征(feature)
特征向量(feature vector)
特征工程(feature enginerring)

下面给出一个手动设计的“王二狗”分类器。首先输入一个“王二狗”,然后我们对“高”、“帅”、“富”三个特征进行提取,根据特征提取的结果,我们就可以做出判别。

1562694145528

特征(feature)

要对图像进行分类,本质上是要通过图像的某些特征对图像进行判别。
在王二狗的例子中,我们提取了他的三个特征:“高”、“帅”、“富”。

特征向量(feature vector)

将提取到的多个特征放在一起,就叫做特征向量。

特征工程(feature enginerring)

找到特征的过程一般称为特征工程。

图像分类的难点:特征非常难以设计

本节名词列表
初级特征(low-level feature)
高级特征(high-level feature)
手工设计的特征(hand-crafted feature)

判断王二狗只需要一个手动设计的分类器即可,而在图像的分类上则需要借助更先进的手段,例如深度学习,这是因为图像分类的一个显著难点就是特征难以提取。

初级特征(low-level feature)

图像上最基础的特征就是初级特征,例如:圆弧、线等等。

高级特征(high-level feature)

高级特征是例如“有眼睛”、“有脸”、“有腿”这样的高层次显著特征。

机器视觉的特征非常难以设计,尤其是介于初级特征与高级特征中间的中级特征,例如:眼睛、腿、脸是怎样用低级特征组合出来的。传统的机器视觉算法通过人工的方式设计了很多特征,例如HOG,SIFT,SURF等,取得了一定的成果,但是也存在瓶颈。

手工设计的特征(hand-crafted feature)

深度学习基本法:特征提取+分类

本节名词列表
可分(separable)
特征提取(feature extraction)
特征学习(feature learning)
表示学习(representation learning)

可分(separable)

例如:我与王二狗是否有钱这一特征,是容易区分的,称之为可分;而让机器看长得一模一样的双胞胎照片,则缺乏能够将二者取分开来的特征,称之为不可分。
能否找到足够的特征让机器能够完成分类是十分关键的一点。

特征提取(feature extraction)

将特征提取出来的过程。深度学习可以自动完成这一过程。

特征学习(feature learning)

深度学习具备自动完成特征提取,称其为具备特征学习的能力。

表示学习(representation learning)

用数字/向量/矩阵等方法来表达现实世界中的物体,而且这种表达方式有利于后续的分类或者其他决策问题。

特征的可分性决定分类器的上限,分类方法(神经网络?随机森林?)决定接近这个上限的程度。
深度学习的关键之处在于能够进行特征学习,自行根据训练数据学习出特征。

在分类问题上,如果数据量并不是非常大、类别不是非常多、而且具备非常好的人工提取feature,那么神经网络相对于随机森林、支持向量机等传统方法并没有非常明显的优势。而深度学习在更大的数据量下、处理更复杂的任务时,能够发挥长处,如下图所示:

1562694154312

与大脑工作机制的关系

本节名词列表
突触(synapse)
特征提取(V1, Primary Visual Cortex)

深度学习的部分做法可以从大脑的工作机制中得到印证和启发,例如:分级特征提取、从数据中学习、神经元的感受野等,但是大部分的工作仍然与人脑的关系较远。

突触(synapse)

一个神经元的输入端。

特征提取(V1, Primary Visual Cortex)

人眼看到的信息首先传到初级视皮层(V1)进行特征提取,然后再传到V2等进行更高级的特征提取。

神经网络的基本组成单元:神经元、层

神经元:从加权和开始

本节名词列表
输入(input)
输出(output)
神经元(neuron)
加权和(weighted sum)
连接权重(weights)
偏置(bias)

神经元最基本的工作原理就是加权和。
下面给出一个神经元的工作过程:
神经元
基本写法:y=x_1w_1+x_2w_2+x_3w_3
求和写法:y=\sum{x_iw_i}
向量写法:y=x\cdot w

输入(input)
输出(output)
神经元(neuron)
加权和(weighted sum)
连接权重(weights)

神经元的任务,就是将各项输入乘上连接权重并求和,得到加权和后输出。

偏置(bias)

如果将加权和再加上一个常数项b,则这个常数项就称为偏置。

深度学习所使用的神经网络可以看作成千上万神经元进行组合,每一个神经元的功能都非常简单,但是组合起来之后可以实现复杂的功能,这一点与人脑十分类似。

通过激活函数引入非线性

本节名词列表
非线性(non-linearity)
线性可分(linearly seperable)
激活函数(activation function)

非线性(non-linearity)
线性可分(linearly seperable)

在二维状况下,如左图,画一条直线可以将图中的蓝色和黄色的部分分开,这种情况为线性可分。而如右图,则无法通过一条简单的直线对蓝色黄色两部分进行分割,这种情况为线性不可分。
线性可分

激活函数(activation function)

如果网络中的每一个神经元都是线性的,那么最后的总效果也只能是线性的,这样我们的网络没有办法处理线性不可分的问题。因此,我们要为网络引入非线性模块,这个非线性模块就是下图中的f(),我们称之为激活函数。

下面给出一张包含激活函数的神经元图:
激活函数
基本写法:y=f(x_1w_1+x_2w_2+x_3w_3)
求和写法:y=f(\sum{x_iw_i})
向量写法:y=f(x\cdot w)

常用激活函数

本节名词列表
Sigmoid
ReLU
TanH

Sigmoid

函数表达式:f(x)=\frac{1}{1+e^{-x}}
SIGMOID
特点:
* 平滑
* 有界:值域在0到1之间
* 梯度在远离0的位置很小(会引起梯度消失)

ReLU

函数表达式:f(x)=\begin{cases}
0, &x<0\cr x, &x\geq0\end{cases}

relu
特点:
* 不平滑
* 无界
* 梯度为0或1

TanH

函数表达式:tanh(x)=\frac{2}{1+e^{-2x}}-1
tanh

全连接层

本节名词列表
全连接层(fully-connected layer, FC, Dence)

把许多个神经元排布在一层,就构成了层(layer)。

全连接层(fully-connected layer, FC, Dence)

每一个神经元的输入都是上一层所有神经元的输出。王二狗的例子中,框出的这一层,所有的输入都来自于上一层中的输出,所以为全连接层。

堆叠更多神经元层

本节名词列表
隐含层(hidden layer)
输入层(input layer)
输出层(output layer)

下面给出一个神经元层堆叠起来的示意图

隐含层(hidden layer)

上图中,中间两层即为隐含层。

输入层(input layer)

上图中最左边接收输入的层即为输入层。

输出层(output layer)

上图中最右边的即为输出层。

所谓深度学习,就是网络越来越深,层数越来越多。

深度学习在图像方向的扛把子:卷积神经网络(CNN)

卷积神经网络

本节名词列表
卷积神经网络(convolutional neural network, CNN)
局部性(locality)

如果把全连接层直接应用于图像,将导致网络参数极多,网络极大,难以实际使用。而且,将全连接层直接应用于图像的方案是没有必要的,因为图像的特征具有局部性。对此我们采用的方案是:卷积结构。
下图给出了一张Le-Net5卷积神经网络的示意图:

卷积神经网络(convolutional neural network, CNN)

包含卷积计算及深度结构的前馈神经网络。卷积神经网络与之前提到的网络一样,也是一层一层的神经元,但所使用的连接方式不是之前提到的全连接,而是下面将讲到的卷积结构。

局部性(locality)

从人脑的结构出发,研究证明,人脑中的神经元不会与之前的所有的神经元相连接,例如,初级视皮层上的神经元不会与视网膜上的每一个神经元,而是V1上的每一个神经元只看到视网膜上的一小部分。

卷积操作

本节名词列表
卷积(convolution)
卷积核(kernel)
滤波器(filter)
特征图(feature map)

卷积(convolution)
卷积核(kernel)

下面给出了一张卷积操作的示意图

其中蓝色的部分可以看作输入的图片,灰色的移动部分我们将其称为卷积核,而右边的绿色的部分则是这个卷积操作的输出。我们让卷积核在输入上“扫”过去,就会得到一个输出。卷积核在每个位置,把卷积核上的每一个数字和输入上对应位置的数字进行相乘,再把乘积加起来,就得到了输出。这一过程本质上依然是加权和,以上图为例,加权和的输入即为蓝色部分的数字,权重即为灰色的卷积核上的数字,得到的输出即为绿色部分。

下面再给出一张卷积的示意图,展示和卷积计算的过程。

下面给出一张卷积操作的示意图,去掉了数字,便于理解。

滤波器(filter)
特征图(feature map)

那么我们为什么要进行卷积操作呢?我们可以将卷积理解为一个特征提取的过程,而卷积核表述了我们要提取的特征,最后的结果我们称之为特征图。下面用一个例子来说明:

上图的左侧有一个图像中“竖直直线”的示意图,其特征是水平方向上有数值突变,而竖直方向上没有变化。我们分别用两个不同的卷积核“卷”过这幅图片,卷积核A卷过的结果是,在竖线处出现了一列数字2,而卷积核B卷过的结果是全为0。这里的卷积核A和B分别代表了我们要找的不同特征,卷积核A表示找竖线,而卷积核B表示找横线,最终得出了不同的结果。

卷积操作完成了一个“滤波”的过程,将特定的图像特征提取出来,所以卷积核也常称为滤波器。

下图展示了一个对图像进行卷积操作的过程。

通过训练,卷积层可以学习到更加复杂的特征以完成更加复杂的任务:

池化/采样

本节名词列表
池化/采样(pooling)
降采样/下采样(down sampling)
平均池化(average pooling)
最大池化(max pooling)
平移不变性(translation invariant)

池化/采样(pooling)

如上图所示,中间4×4的矩阵,经过池化,就变成了一个2×2的矩阵。
池化层可以看作采样,通常会降低层的长度与高度(最常见的是长宽减半)。

平均池化(average pooling)
最大池化(max pooling)

上图右上方展示的是平均池化的过程,他对每一个2×2的小区域求平均值,得出新的结果,例如绿色部分的结果15,为原矩阵中绿色部分的平均值。
上图右下方展示的是最大池化的过程,他取每一个每一个2×2的小区域中的最大值作为新的结果,例如绿色部分的结果21,为原矩阵中绿色部分的最大值。
历史上平均池化曾起到重要的作用,而如今一般使用最大池化,可以理解为最大池化能够保留图像中“最有用”的信息。

降采样/下采样(down sampling)

经过上述的过程,图像的分辨率下降了,所以我们称之为降采样/下采样。

平移不变性(translation invariant)

池化产生了一定的不变性,可以认为是一种选取最有用信息的操作。例如上图中第一行第二列位置的8如果产生微小变化,例如变成了9,经过最大池化,绿色部分的结果仍为21。这使我们的模型不会因为输入的微小变化产生区别很大的结果。

卷积/池化层的参数

本节名词列表
核尺寸(kernal size)
感受野(receptive field)
步幅(stride)
填充(padding)

步幅(stride)

在卷积操作这一节中展示的动图中,卷积核是“一格一格地”卷过去的,我们称步幅为1。


而当步幅增大到2时:

可以发现当步幅为1时,输出与输入的规模是一致的。当步幅大于1时,输出的规模比输入小。
卷积层的步幅一般为1,池化层的步幅一般大于1,所以池化层完成了降采样的过程。

填充(padding)

上面几张图中,周围围着的一圈0即为填充,当我们在卷积的时候,卷积核在边界时可能会超出输入的范围,这时我们需要在周围加上一圈填充。

核尺寸(kernal size)

在本节的几张图中,卷积核的尺寸为3×3,而在池化/采样一节中,核的尺寸为2×2。

感受野(receptive field)

由神经科学而来的词汇,原来指例如初级视皮层上一个神经元接收视网膜上信息的范围。在卷积/池化中我们也借用了这样的词汇。一般核尺寸越大它的感受野就越大。

卷积/池化“层”实际上是三维的

本节名词列表
深度(depth)

深度(depth)

实际上,每一层的输入是三维的(长卷积核种类的数量),输出也是三维的(长卷积核种类的数量)。而这个第三维的参数就是深度。

对于输入的图片A,经过一次操作,在C1处得到了六张“方片”,每一张“方片”都是一个卷积核(滤波器)所得到的特征图。

SoftMax

本节名词列表
独热编码(one hot encoder)
概率分布(probability distribution)
SoftMax

独热编码(one hot encoder)

在最开始的王二狗的例子中,我们就用到了独热编码:我们将王二狗分为两种状态(“抱紧”或“滚粗”),在最后一层中用了与状态数量一致的神经元,即两个神经元,而且仅有一种状态为1,其他为0,即结果只为“抱紧”或“滚粗”,两者不可能同时为真。
直观来说独热编码就是,最后一层中,有多少个状态就有多少神经元,而且只有一个状态为1,其他全为0。
而在MNIST的例子中,我们要识别10种不同的手写数字,我们在最后一层中有10个神经元(或11个神经元,即10个数字+不是数字),且只有一种状态概率为1(或接近于1),其他全为0,这也是运用了独热编码。

概率分布(probability distribution)

每项概率都大于等于0,且加起来等于1。

SoftMax

神经网络的输出常常使用独热编码,但是最后一层神经元的输出未必符合概率分布,对此我们使用SoftMax解决

你已经能初步理解经典卷积神经网络VGG的结构了

本节名词列表
VGG(VGG16/VGG19)

VGG(VGG16/VGG19)

VGG是Oxford的Visual Geometry Group在ILSVRC 2014上的相关工作,有两种结构,分别是VGG16和VGG19,两者并没有本质上的区别,只是网络深度不一样,16或19为卷积层+全连接层的数量,不包含池化层和SoftMax,因为他们没有需要训练的参数。
上图所示的即为VGG的示意,可以看到网络不断地进行卷积、池化,最后经过全连接层和SoftMax处理得出结果。

进阶:批标准化层

本节名词列表
批标准化(batch normalization)
正则化(regularizer)

批标准化(batch normalization)

如果每层神经元的输入在训练过程中分布保持一致,网络将更容易收敛,而现有每层神经元的输入来自上一层,而上一层的输出在训练的过程中分布会变化,对此我们的解决方法是,强行让上一层的输入在一组数据中符合一定要求(均值为0,输入为1),这一过程成为批标准化,这是Google的一项重要工作。

正则化(regularizer)

正则化方法是指向原始模型引入额外信息,以便防止过拟合和提高模型泛化性能的一类方法。

更深的网络结构:ResNet

本节名词列表
ResNet
残差(residual)
跨层连接(skip connection)

ResNet
残差(residual)
跨层连接(skip connection)


上图的最上方是ResNet的网络示意图。

深度残差网络ResNet的提出是CNN图像史上的一件里程碑事件,ResNet在ILSVRC和COCO 2015上取得了5项第一其作者何凯明也因此摘得CVPR2016最佳论文奖。

这个网络拥有跨层的连接,区别于前面的第一层→第二层→第三层这样的走法,在这个网络中,会有第二层的输入直接接到第五层,再与第四层的结果加起来再往下走的跨层连接过程,实现了残差的学习。

更宽的网络结构:GoogLeNet

本节名词列表
串接(concatenation)
GoogLeNet
Inception

GoogLeNet

上图为GoogLeNet的示意图。
从左往右看,这个网络依然是一层一层的排布结构,但是在每一层上又有好几个组成部分,也就是说这个网络的宽度就不是1了。

Inception
串接(concatenation)

下图所示的inception结构是GoogLeNet的基本组成部分:

我们可以看到在inception结构中有1×1的卷积、3×3的卷积、5×5的卷积、3×3的池化等等。相当于原来只有一层,而我们现在有了多层并将结果串接起来。对此的直观理解可以是:我们的卷积层在提取特征时究竟采用几x几的卷积核效果最好是比较难确定的,于是我们在这里把各种卷积核的大小都进行尝试。
这里特别讲一下看似没有意义的1×1的卷积,之前已经提到过,卷积层不仅有长和宽,它是一个三维的概念。我们的图像可能不止有一个通道,例如我们常见的RGB色彩模式,就有三个通道,从下图可以看出,卷积操作实际上会把每个通道的计算结果进行叠加,所以1×1的卷积并非是无意义的操作。

真正让深度学习工作起来

####深度学习的本质困难

本节名词列表
模型参数(model parameters)
过拟合(overfitting)
泛化能力(generalization)
核弹厂(NVidia)

模型参数(model parameters)

在王二狗的例子当中,我们一共有八个神经元,每个神经元有三个参数需要调整,那么总共就有24个参数需要调整,可以想象在上面提到的更复杂的情况中,将会有更多的参数出现。机器学习的参数越多,模型就越复杂。
参数多的优势在于,它使机器能够完成更加复杂的学习任务。

过拟合(overfitting)
泛化能力(generalization)

与此同时,参数多也带来许多困难。首先,训练数据和参数数量相比太少,极易发生过拟合。比如在下图中,我们要将蓝色和红色的点区分开来,黑色的线条较好的将两者分割开来了,而绿色的线虽然实际上完美地区分了蓝色和红色的点,但实际上没有学习到红蓝两方的本质特征,缺乏泛化能力。

这好比小明在做习题集时没有理解习题的本质内容,只是在背答案,当遇到新的题目时,如果题目数据发生变化,小明就不能很好的应对。
其次参数太多,训练的难度大、效率低。
对此我们的对策是:第一,收集海量数据(例如ImageNet所做的工作)

核弹厂(NVidia)

第二,爆计算力(堆核弹),使用更强的硬件计算能力对抗复杂的训练工作。
第三,在算法中加入缓解过拟合、加快训练收敛的方法。

防止过拟合的方法:破坏低级不稳定的特征

本节名词列表
Dropout
Noise

在上面小明背答案的例子中,显然我们可以通过如下的方式来逼小明认真学习:改变题目中的数字、随即改变选项顺序、将数学问题包装成应用题……这些方法破坏了一道题的低级特征,这样能够“逼迫”小明去发现题目的高级特征,完成真正的学习。
在深度学习领域,同样地,我们可以通过破坏数据低级不稳定的特征来“逼迫”神经网络抓住事物的本质特征。

Dropout

如下图所示,训练时随机让一些神经网络输出0,相当于随机扔掉一些特征,这逼迫神经网络去学习一些更加稳定的特征,一般图像中事物的本质特征总是组合更多、更加稳定。

Noise

训练时让神经元输出加上一些噪声,为了避免在实际运用时神经网络因为一些噪声而失去作用,在训练时我们就像其中加入一些噪声,使神经网络更加稳定。

神经网络的训练

反向传播算法

本节名词列表
训练(train)
预测(inference)
真值(ground truth)
损失函数(lost function)
成本函数(cost function)
前向传播(forward propagation)
反向传播(back propagation)
链式求导法则(chain rule)
梯度消失(gradient vanishing)
梯度爆炸(gradient exploding)

训练(train)
预测(inference)

训练是指我们将训练数据喂给神经网络,并调整神经网络的参数的过程。
预测就是当我们有了一个神经网络,使用它对输入的数据进行分类等任务的过程。
下图展示了预测的过程:

下图展示了训练的过程:

真值(ground truth)

真值是指监督学习中对一个数据预测结果的标准答案。真值往往由人类标注给出。

损失函数(lost function)
成本函数(cost function)

损失函数一般指对单个样本的做的损失计算,成本函数一般是数据集上总的成本和损失计算。

前向传播(forward propagation)
反向传播(back propagation)

前向传播是指先通过已有的网络进行图像分类,得到结果的过程。反向传播指的是,根据得到的结果计算损失函数,从后至前依次调整每一层参数的过程。

链式求导法则(chain rule)

链式求导法则是反向传播过程中用于调整参数时使用的法则。

梯度消失(gradient vanishing)
梯度爆炸(gradient exploding)

反向传播的过程中会遇到许多问题,例如向前算着算着权值更新的梯度越来越接近于0,称为梯度消失,反之梯度越来越接近于无限大,称为梯度爆炸。

更新参数的基本原理:梯度下降

本节名词列表
导数(derivative)
梯度下降(gradient descent)

导数(derivative)

一个函数在某一点的导数描述了这个函数在这一点附近的变化率。

梯度下降(gradient descent)

那么怎样更新网络中的参数呢?我们做的是一个让梯度下降的过程:我们希望通过梯度下降的过程找到令损失函数最小的一组参数。仿佛我们在一座山上,不知道怎样去山顶,但我们只要一直沿着坡度向上的方向往上走,就可以到达山顶。
下图展示了梯度下降的过程,可以将红色的圆环理解成等高线,我们不断沿登高线垂直方向走,就可以到达山顶。

下图在函数图像上展示了梯度下降的过程。

反向传播算法进阶

本节名词列表
局部极小值(local minimum)
全局最小值(global minimun/absolute minimum)
随机梯度下降(SGD)
冲量(momentum)
学习率(learning rate)
学习率衰减(learning rate decay)

局部极小值(local minimum)
全局极小值(global minimun/absolute minimum)

在做梯度下降的过程中会遇到一些问题,例如,我们找到的极小值可能只是局部范围之内的最小值,而不是整个函数范围内的最小值(全局最小值)。

冲量(momentum)

我们仍然把梯度下降的过程想象成过山坡,在下面这张图中,红点在函数图像上下降到一个“小坑”里就不动了,这个小坑是局部的最低点,但不是全局的最低点,这就是我们上面讲到的局部极小值,它陷入了局部最优。

这里我们引入冲量的概念,可以想象成过山坡时有一股冲劲使得红点能够冲过小坑,进入全局的最小点,下面是引入冲量之后的梯度下降过程:

学习率(learning rate)

学习率控制着我们基于损失梯度调整神经网络权值的速度,学习率越小,沿着损失梯度下降的速度越慢。看似使用小的学习率可以避免错过任何局部最优解,但也意味着要花更多时间来收敛,尤其是如果我们处于曲线的至高点。而学习率设置过大,就会出现振荡,无法收敛,如下图:

新权值 = 当前权值 – 学习率 × 梯度

学习率衰减(learning rate decay)

学习率大,会发散,学习率小,会变慢。那么我们能否让学习率有大小变化(先大后小)呢?这一过程就是学习率衰减。如果我们反复让学习率变大变小变大变小,就称为循环学习率衰减。

随机梯度下降(SGD)

面对我们上面提到的找“谷底”的问题,我们有不同的Solver(优化算法),下图中可以看到不同的优化算法针对同一个找谷底的问题,表现上的不同:

我们评价不同优化算法的标准就是,他们能否克服局部最优解,能否收敛、快速收敛。

重用预先训练的特征:Fine-tuning

本节名词列表
Fine-tuning
冻结层参数(Freeze Layers)

Fine-tuning
冻结层参数(Freeze Layers)

在实际应用中,再大数据集上的训练非常耗时,而很多问题的数据集又很小,对此,针对不同任务,图像的很多特征是相通的,可以重用在大数据集上学到的特征,具体的操作是,在大数据集上训练网络,保持卷积层不变(可选),重新初始化全连接层,再训练。
Fine-tuning就是把现成的模型进行微调然后再作少量训练,主要用于样本数量不足的情形。
冻结层参数就是上面提到的,保持部分层参数不变的操作。
下图展示了在ImageNet(1000类图片)上训练网络,fine-tune成20类图片分类问题的过程:

当然还有很多东西是需要的

  • 运气
  • 经验
  • 网络结构非常重要,但是实践中数据准备、训练方式等等的影响不亚于网络结构本身。

训练、预测都需要巨大的运算量

本节名词列表
GPU
CUDA
数据并行(data parallelism)
模型并行(model parallelism)
定点化(quantization)
剪枝(pruning)
稀疏(sparse)

GPU
CUDA
数据并行(data parallelism)
模型并行(model parallelism)

卷积核全连接层参数量和运算量都非常巨大,好在它的并行度比较高,可以使用GPU或专用硬件(FPGA, ASIC)并行计算。CUDA是一种由NVIDIA推出的通用并行计算架构,该架构使GPU能够解决复杂的计算问题。

除了并行计算以外,模型本身也有大量可以优化、简化的空间:

定点化(quantization)

比如,我们刚刚提到的网络中,参数都是用浮点数进行表示的,我们可以将它定点化,方便芯片进行运算。

剪枝(pruning)
稀疏(sparse)

又如我们刚刚提到的网络中,一个神经元可能连接了一百个神经元,但实际上也许并没有必要连接这么多,我们可以对其进行剪枝,精简网络的结构。稀疏模型可以将大量的冗余变量去除,简化了模型的同时保留数据集中最重要的信息。

重要工作和前沿方向

图像领域一些重要方向

本节名词列表
目标检测(object detection)
语义分割(semantic segmentation)
实例分割(instance segmentation)

真正的人类视觉比图像分类复杂得多,因此还有许多重要的工作:

从分类到目标检测:RCNN, Fast RCNN, Faster RCNN, SSD, YOLO

目标检测(object detection)

从图片中判别及找出存在的物体。

语义分割:FCN, Mask FRCNN

语义分割(semantic segmentation)

不仅识别图中有什么物体,还对边界进行划分。

实例分割(instance segmentation)

另外,为了将深度学习的能力下放到边缘设备上,模型小型化(SqueezeNet, ShuffleNet)成为趋势。

推荐的深度学习框架

框架的作用:
* 预定义的操作、层
* 自动求导
* GPU加速、分布式
* 可视化等调试工具
* 数据格式处理
* ……

推荐的框架:
* TensorFlow:谷歌主导,强烈推荐
* Keras:强烈推荐,入门者建议使用
* Caffe2:推荐学习
* MXNet:推荐学习

推荐阅读

斯坦福2017课程:Convolutonal Neural Neiworks for Visual Recognition
http://cs231n.stanford.edu

周志华《机器学习》

* 教科书式,全面而难度适中
* 适合有一定数学基础(高年级本科生以上)
* 可以用于机器学习入门

李嘉璇《TensorFlow技术解析与实战》

* 实战、动手向,阅读难度低
* 需要基本的编程能力
* 可以用于程序员快速入门深度学习

Ian Goodfellow, Yoshua Bengio, Aaron Courville 《深度学习》

* 需要数学基础较好
* 阅读难度较大
* 不建议作为入门的机器学习书
* 入门之后深入学习

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