TVM编译器推理加速模型

这篇具有很好参考价值的文章主要介绍了TVM编译器推理加速模型。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


一、TVM

TVM是一个开源的端到端优化机器学习编译器,目的是加速模型在任意硬件上的计算。
一般情况下如果实在intel的cpu上面部署可能用OpenVino,N卡上面肯定TensorRT,arm架构机器可能会用Ncnn等,意味着要针对每个框架做部署,这里面涉及到的转换非常复杂,部署过的就知道有多少坑在里面。而TVM最重要的一块就是自动生成和优化模型的基础架构,具有更好的性能,这张图简单说就是不管你什么深度学习框架不管什么硬件部署都能通过TVM搞定。
编译器的基本结构如下:
编译前端: 接收C/C++/Java等不同语言,进行代码生成,吐出IR,TVM这里相当于是输入模型的环节
编译器中端:接收IR,进行不同编译器后端可以共享的优化,如常量替换,死代码消除,循环优化等,吐出优化后的IR
编译器后端:接收优化后的IR,进行不同硬件的平台相关优化与硬件指令生成,吐出目标文件

TVM编译器推理加速模型,深度学习,人工智能,机器学习,计算机视觉,opencv

二、示例代码

示例代码使用的同样是最简单的mobilenet_v3分类模型,是使用pytorch训练然后转onnx,可以参考前面几个文章有详细代码https://blog.csdn.net/Y_snower/article/details/125443366,首先安装tvm相关环境。我这里是python3.7 tvm1.0.0 onnx1.10.0

1.TVM文件生成

代码中针对tuning_option,在官方文档中这样说的For a production job, you will want to set the number of trials to be larger than the value of 20 used here. For CPU we recommend 1500, for GPU 3000-4000. The number of trials required can depend on the particular model and processor, so it’s worth spending some time evaluating performance across a range of values to find the best balance between tuning time and model optimization.
对cpu和gpu给出了不同的推荐值,实测下来选择不同的值对最终的推理速度也有影响。
代码如下:

import tvm.auto_scheduler as auto_scheduler
from tvm.autotvm.tuner import XGBTuner
from tvm import autotvm
import onnx
import numpy as np
import tvm
from tvm import relay


onnx_model = onnx.load('tiankong.onnx')  # 加载onnx模型,当然也可以用tvmc来load
target = tvm.target.Target('llvm -mcpu=skylake')  # 因为是cpu上的优化,所以llvm,GPU的话是cuda
# target = tvm.target.Target('llvm -mcpu=core-avx2')
input_name = 'input'
shape_dict = {input_name: (1, 1, 128, 128)}  # 输入的shape,因为之前一直训练的灰度所以是1,1不是1,3
mod, params = relay.frontend.from_onnx(onnx_model, shape_dict)
number = 10
repeat = 1
min_repeat_ms = 0
timeout = 10
# create a TVM runner
# min_repeat_ms is a value that specifies how long need to run configuration test. If the number of repeats falls under this time, it will be increased. This option is necessary for accurate tuning on GPUs, and is not required for CPU tuning. Setting this value to 0 disables it.
runner = autotvm.LocalRunner(
    number=number,  # number specifies the number of different configurations that we will test
    repeat=repeat,  # repeat specifies how many measurements we will take of each configuration
    timeout=timeout,  # in seconds,The timeout places an upper limit on how long to run training code for each tested configuration.
    min_repeat_ms=min_repeat_ms,  
    enable_cpu_cache_flush=True,
)

#以下这部分是计算优化
tuning_option = {
    "tuner": "xgb",
    "trials": 1500,
    "early_stopping": 100,
    "measure_option": autotvm.measure_option(
        builder=autotvm.LocalBuilder(build_func="default"), runner=runner  # 默认的是XGBOOST优化
    ),
    "tuning_records": "resnet-50-v2-autotuning.json",  # 这里名称自己写,官方示例这样的我没改无所谓
}
# begin by extracting the tasks from the onnx model
tasks = autotvm.task.extract_from_program(mod["main"], target=target, params=params)

# Tune the extracted tasks sequentially.
for i, task in enumerate(tasks):
    prefix = "[Task %2d/%2d] " % (i + 1, len(tasks))
    tuner_obj = XGBTuner(task, loss_type="rank")
    tuner_obj.tune(
        n_trial=min(tuning_option["trials"], len(task.config_space)),
        early_stopping=tuning_option["early_stopping"],
        measure_option=tuning_option["measure_option"],
        callbacks=[
            autotvm.callback.progress_bar(tuning_option["trials"], prefix=prefix),
            autotvm.callback.log_to_file(tuning_option["tuning_records"]),
        ],
    )

with autotvm.apply_history_best(tuning_option["tuning_records"]):
    with tvm.transform.PassContext(opt_level=3):
        graph, lib, params = relay.build(mod, target, params=params)       
# 输出TVM需要的三个文件
from tvm.contrib import graph_runtime
libpath = "test.so"
lib.export_library(libpath)
graph_json_path = 'test.json'
with open(graph_json_path, 'w') as f:
    f.write(graph)

param_path = "./test.params"
with open(param_path, 'wb') as fo:
    fo.write(relay.save_param_dict(params))

2.TVM推理

代码如下:

import time
import numpy as np
import tvm
import tvm.relay as relay
from tvm.contrib import graph_runtime
import cv2


def preprocess(img):
    h, w = img.shape[:2]
    if h < w:
        distance = int((w - h) / 2)
        img = cv2.copyMakeBorder(img, distance, distance, 0, 0, cv2.BORDER_CONSTANT, value=0)
    else:
        distance = int((h - w) / 2)
        img = cv2.copyMakeBorder(img, 0, 0, distance, distance, cv2.BORDER_CONSTANT, value=0)
    img = cv2.resize(img, (128, 128), cv2.LINE_AA)
    img = img.astype(np.float32) / 255.0
    img = img[np.newaxis, np.newaxis, :, :]
    img = np.array(img, dtype=np.float32)
    return img


if __name__ == "__main__":
    test_json = "test.json"
    test_lib = "test.so"
    test_params = "test.params"
    loaded_json = open(test_json).read()
    loaded_lib = tvm.runtime.load_module(test_lib)
    loaded_params = bytearray(open(test_params, 'rb').read())

    img = cv2.imread("my_test.jpg", 0)
    img_input = preprocess(img)  # 预处理方法,按照自己的方法改造
    ctx = tvm.cpu(0)
    module = graph_runtime.create(loaded_json, loaded_lib, ctx)
    module.load_params(loaded_params)
    start = time.time()
    for i in range(1000):
        module.set_input("input", img_input)
        module.run()
        out_deploy = module.get_output(0).numpy()
        out = np.argmax(out_deploy)  # 输出分类结果,我这里二分类输出0或者1的值
        # print(out_deploy, out)
    print(time.time()-start)

总结

从推理测试结果来看,如果不做优化自动搜索参数这一步,在cpu上循环识别1000次大概4ms/次,优化后的速度在2.7ms/次,后面会把代码上传至 https://github.com/Ysnower/pytorch-static-quant C++的推理后期会写,如有错误之处望指正。文章来源地址https://www.toymoban.com/news/detail-804474.html

到了这里,关于TVM编译器推理加速模型的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 深度学习编译器相关的优秀论文合集-附下载地址

    公司排名不分先后 目前在AI芯片编译器领域,有很多大公司在进行研究和开发。以下是一些主要的公司和它们在该领域的研究时间: 英伟达(NVIDIA):英伟达是一家全球知名的图形处理器制造商,其在AI芯片编译器领域的研究和开发始于2016年左右。 英特尔(Intel):英特尔是

    2023年04月11日
    浏览(37)
  • 深度学习模型部署-番外-TVM机器学习编译

    图片来自知乎大佬的文章 机器学习编译是指:将模型从训练形式转变为部署模式 训练模式:使用训练框架定义的模型 部署模式:部署所需要的模式,包括模型每个步骤的实现代码,管理资源的控制器,与应用程序开发环境的接口。 这个行为和传统的编译很像,所以称为机器

    2024年03月18日
    浏览(31)
  • c编译器学习02:chibicc文档翻译

    先粗略地看一遍作者的书籍。 https://www.sigbus.info/compilerbook# “低レイヤを知りたい人のためのCコンパイラ作成入門” 为想了解底层的人准备的C编译器制作入门 Rui Ueyama ruiu@cs.stanford.edu 2020-03-16 https://www.sigbus.info/ 植山瑠偉 谷歌软件工程师 我的专业知识涵盖从 HTML/JavaScript 到硬

    2024年02月21日
    浏览(59)
  • Linux的学习之路:6、Linux编译器-gcc/g++使用

    本文主要是说一些gcc的使用,g++和gcc使用一样就没有特殊讲述。 目录 摘要 一、背景知识 二、gcc如何完成 1、预处理(进行宏替换) 2、编译(生成汇编) 3、汇编(生成机器可识别代码 4、链接(生成可执行文件或库文件) 5、函数库 6、静态库和动态库 7、gcc选项 三、思维导图

    2024年04月23日
    浏览(38)
  • 嵌入式C语言自我修养《GNU C编译器扩展语法》学习笔记

    目录 一、C语言标准和编译器 二、指定初始化 三、宏构造“利器”:语句表达式 四、typeof与container_of宏 五、零长度数组 六、属性声明:section  七、属性声明:aligned  C语言标准的发展过程: ● KR C. ● ANSI C. ● C99. ● C11. 指定初始化结构体成员:         和数组类似,

    2024年02月08日
    浏览(38)
  • 链接文件学习(七):英飞凌MCU Tasking编译器LSL链接文件解析 及代码变量定位方法

    目录   1、Tasking的链接文件 1.1、DSRAM中的数据存放 1.2、PFlash中的代码存放 1.3、LMU 1.4、PSRAM 1.5、UCB 2、代码与变量定位

    2024年02月07日
    浏览(42)
  • Latex安装与环境配置(TeXlive、TeXstudio与VS code的安装)编译器+编辑器与学习应用

    TeXlive 配置Tex排版系统需要安装编译器+编辑器。TeX 的源代码是后缀为  .tex  的纯文本文件。使用任意纯文本编辑器,都可以修改  .tex  文件:包括 Windows 自带的记事本程序,也包括专为 TeX 设计的编辑器(TeXworks, TeXmaker, TeXstudio, WinEdt 等),还包括一些通用的文本编辑器(

    2024年02月14日
    浏览(44)
  • C++输出编译器名称和版本以及编译器位数、C/C++常见编译器

    常见的C/C++编译器主要包括以下几种: GCC (GNU Compiler Collection):GCC是一个广泛使用的编译器套件,支持多种编程语言,包括C、C++、Objective-C等。它具有强大的优化能力和跨平台支持,并且被广泛应用于各种操作系统和开发环境。 Clang :Clang是基于LLVM的编译器前端,支持C、

    2024年02月13日
    浏览(34)
  • python在线编译器搭建,python在线编译器源码

    本篇文章给大家谈谈python在线编译器搭建,以及python在线编译器源码,希望对各位有所帮助,不要忘了收藏本站喔。 1. PyCharm集成开发环境 2. PyCharm的下载与安装 3. Pycharm的使用 3.1 创建Python项目 3.2 创建子目录 3.3 创建Python文件 3.4 切换解释器 3.5 常用快捷键 4. Pycharm常用配置

    2024年03月25日
    浏览(46)
  • 编译器(Compiler)及C/C++编译器安装(c+安装)

    目录 一、常用编程语言的编译器(compiler) 概述 二、GCC、MinGW、MinGW-w64 、TDM-GCC、Cygwin、MSYS、MSYS2的区别 三、MinGW-w64编译器套件下载及安装 四、MinGW-w64安装后,windows环境变量配置(设置) 五、编译器的运行及其与开发环境的关系、编译器的来源        机器语言是一种计算机指

    2024年02月07日
    浏览(52)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包