范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文
国学影视

TVM加速模型,优化推断

  TVM 是一个开源深度学习编译器,可适用于各类 CPUs, GPUs 及其他专用加速器。它的目标是使得我们能够在任何硬件上优化和运行自己的模型。不同于深度学习框架关注模型生产力,TVM 更关注模型在硬件上的性能和效率。
  本文只简单介绍 TVM 的编译流程,及如何自动调优自己的模型。更深入了解,可见 TVM 官方内容: 文档: https://tvm.apache.org/docs/ 源码: https://github.com/apache/tvm 编译流程
  TVM 文档  Design and Architecture[1]  讲述了实例编译流程、逻辑结构组件、设备目标实现等。其中流程见下图:
  从高层次上看,包含了如下步骤: 导入(Import):前端组件将模型提取进 IRModule,其是模型内部表示(IR)的函数集合。 转换(Transformation):编译器将 IRModule 转换为另一个功能等效或近似等效(如量化情况下)的 IRModule。大多转换都是独立于目标(后端)的。TVM 也允许目标影响转换通道的配置。 目标翻译(Target Translation):编译器翻译(代码生成) IRModule 到目标上的可执行格式。目标翻译结果被封装为 runtime.Module,可以在目标运行时环境中导出、加载和执行。 运行时执行(Runtime Execution):用户加载一个 runtime.Module 并在支持的运行时环境中运行编译好的函数。 调优模型
  TVM 文档  User Tutorial[2]  从怎么编译优化模型开始,逐步深入到 TE, TensorIR, Relay 等更底层的逻辑结构组件。
  这里只讲下如何用 AutoTVM 自动调优模型,实际了解 TVM 编译、调优、运行模型的过程。原文见  Compiling and Optimizing a Model with the Python Interface (AutoTVM)[3] 。准备 TVM
  首先,安装 TVM。可见文档  Installing TVM[4] ,或笔记「TVM 安装」[5] 。
  之后,即可通过 TVM Python API 来调优模型。我们先导入如下依赖: import onnx from tvm.contrib.download import download_testdata from PIL import Image import numpy as np import tvm.relay as relay import tvm from tvm.contrib import graph_executor 准备模型,并加载
  获取预训练的 ResNet-50 v2 ONNX 模型,并加载: model_url = "".join(     [         "https://github.com/onnx/models/raw/",         "main/vision/classification/resnet/model/",         "resnet50-v2-7.onnx",     ] )  model_path = download_testdata(model_url, "resnet50-v2-7.onnx", module="onnx") onnx_model = onnx.load(model_path) 准备图片,并前处理
  获取一张测试图片,并前处理成 224x224 NCHW 格式: img_url = "https://s3.amazonaws.com/model-server/inputs/kitten.jpg" img_path = download_testdata(img_url, "imagenet_cat.png", module="data")  # Resize it to 224x224 resized_image = Image.open(img_path).resize((224, 224)) img_data = np.asarray(resized_image).astype("float32")  # Our input image is in HWC layout while ONNX expects CHW input, so convert the array img_data = np.transpose(img_data, (2, 0, 1))  # Normalize according to the ImageNet input specification imagenet_mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1)) imagenet_stddev = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1)) norm_img_data = (img_data / 255 - imagenet_mean) / imagenet_stddev  # Add the batch dimension, as we are expecting 4-dimensional input: NCHW. img_data = np.expand_dims(norm_img_data, axis=0) 编译模型,用 TVM Relay
  TVM 导入 ONNX 模型成 Relay,并创建 TVM 图模型: target = input("target [llvm]: ") if not target:     target = "llvm"     # target = "llvm -mcpu=core-avx2"     # target = "llvm -mcpu=skylake-avx512"  # The input name may vary across model types. You can use a tool # like Netron to check input names input_name = "data" shape_dict = {input_name: img_data.shape}  mod, params = relay.frontend.from_onnx(onnx_model, shape_dict)  with tvm.transform.PassContext(opt_level=3):     lib = relay.build(mod, target=target, params=params)  dev = tvm.device(str(target), 0) module = graph_executor.GraphModule(lib["default"](dev ""default""))
  其中  target  是目标硬件平台。llvm  指用 CPU,建议指明架构指令集,可更优化性能。如下命令可查看 CPU:$ llc --version | grep CPU   Host CPU: skylake $ lscpu
  或直接上厂商网站(如  Intel  Products[6] )查看产品参数。运行模型,用 TVM Runtime
  用 TVM Runtime 运行模型,进行预测: dtype = "float32" module.set_input(input_name, img_data) module.run() output_shape = (1, 1000) tvm_output = module.get_output(0, tvm.nd.empty(output_shape)).numpy() 收集优化前的性能数据
  收集优化前的性能数据: import timeit  timing_number = 10 timing_repeat = 10 unoptimized = (     np.array(timeit.Timer(lambda: module.run()).repeat(repeat=timing_repeat, number=timing_number))     * 1000     / timing_number ) unoptimized = {     "mean": np.mean(unoptimized),     "median": np.median(unoptimized),     "std": np.std(unoptimized), }  print(unoptimized)
  之后,用以对比优化后的性能。 后处理输出,得知预测结果
  输出的预测结果,后处理成可读的分类结果: from scipy.special import softmax  # Download a list of labels labels_url = "https://s3.amazonaws.com/onnx-model-zoo/synset.txt" labels_path = download_testdata(labels_url, "synset.txt", module="data")  with open(labels_path, "r") as f:     labels = [l.rstrip() for l in f]  # Open the output and read the output tensor scores = softmax(tvm_output) scores = np.squeeze(scores) ranks = np.argsort(scores)[::-1] for rank in ranks[0:5]:     print("class="%s" with probability=%f" % (labels[rank], scores[rank])) 调优模型,获取调优数据
  于目标硬件平台,用 AutoTVM 自动调优,获取调优数据: import tvm.auto_scheduler as auto_scheduler from tvm.autotvm.tuner import XGBTuner from tvm import autotvm  number = 10 repeat = 1 min_repeat_ms = 0  # since we"re tuning on a CPU, can be set to 0 timeout = 10  # in seconds  # create a TVM runner runner = autotvm.LocalRunner(     number=number,     repeat=repeat,     timeout=timeout,     min_repeat_ms=min_repeat_ms,     enable_cpu_cache_flush=True, )  tuning_option = {     "tuner": "xgb",     "trials": 10,     "early_stopping": 100,     "measure_option": autotvm.measure_option(         builder=autotvm.LocalBuilder(build_func="default"), runner=runner     ),     "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"]),         ],     )
  上述  tuning_option  选用的 XGBoost Grid  算法进行优化搜索,数据记录进 tuning_records 。重编译模型,用调优数据
  重新编译出一个优化模型,依据调优数据: with autotvm.apply_history_best(tuning_option["tuning_records"]):     with tvm.transform.PassContext(opt_level=3, config={}):         lib = relay.build(mod, target=target, params=params)  dev = tvm.device(str(target), 0) module = graph_executor.GraphModule(lib["default"](dev ""default""))   # Verify that the optimized model runs and produces the same results  dtype = "float32" module.set_input(input_name, img_data) module.run() output_shape = (1, 1000) tvm_output = module.get_output(0, tvm.nd.empty(output_shape)).numpy()  scores = softmax(tvm_output) scores = np.squeeze(scores) ranks = np.argsort(scores)[::-1] for rank in ranks[0:5]:     print("class="%s" with probability=%f" % (labels[rank], scores[rank])) 对比调优与非调优模型
  收集优化后的性能数据,与优化前的对比: import timeit  timing_number = 10 timing_repeat = 10 optimized = (     np.array(timeit.Timer(lambda: module.run()).repeat(repeat=timing_repeat, number=timing_number))     * 1000     / timing_number ) optimized = {"mean": np.mean(optimized), "median": np.median(optimized), "std": np.std(optimized)}  print("optimized: %s" % (optimized)) print("unoptimized: %s" % (unoptimized))
  调优模型,整个过程的运行结果,如下: $ time python autotvm_tune.py # TVM 编译运行模型 ## Downloading and Loading the ONNX Model ## Downloading, Preprocessing, and Loading the Test Image ## Compile the Model With Relay target [llvm]: llvm -mcpu=core-avx2 One or more operators have not been tuned. Please tune your model for better performance. Use DEBUG logging level to see more details. ## Execute on the TVM Runtime ## Collect Basic Performance Data {"mean": 44.97057118016528, "median": 42.52320024970686, "std": 6.870915251002107} ## Postprocess the output class="n02123045 tabby, tabby cat" with probability=0.621104 class="n02123159 tiger cat" with probability=0.356378 class="n02124075 Egyptian cat" with probability=0.019712 class="n02129604 tiger, Panthera tigris" with probability=0.001215 class="n04040759 radiator" with probability=0.000262 # AutoTVM 调优模型 [Y/n] ## Tune the model [Task  1/25]  Current/Best:  156.96/ 353.76 GFLOPS | Progress: (10/10) | 4.78 s Done. [Task  2/25]  Current/Best:   54.66/ 241.25 GFLOPS | Progress: (10/10) | 2.88 s Done. [Task  3/25]  Current/Best:  116.71/ 241.30 GFLOPS | Progress: (10/10) | 3.48 s Done. [Task  4/25]  Current/Best:  119.92/ 184.18 GFLOPS | Progress: (10/10) | 3.48 s Done. [Task  5/25]  Current/Best:   48.92/ 158.38 GFLOPS | Progress: (10/10) | 3.13 s Done. [Task  6/25]  Current/Best:  156.89/ 230.95 GFLOPS | Progress: (10/10) | 2.82 s Done. [Task  7/25]  Current/Best:   92.33/ 241.99 GFLOPS | Progress: (10/10) | 2.40 s Done. [Task  8/25]  Current/Best:   50.04/ 331.82 GFLOPS | Progress: (10/10) | 2.64 s Done. [Task  9/25]  Current/Best:  188.47/ 409.93 GFLOPS | Progress: (10/10) | 4.44 s Done. [Task 10/25]  Current/Best:   44.81/ 181.67 GFLOPS | Progress: (10/10) | 2.32 s Done. [Task 11/25]  Current/Best:   83.74/ 312.66 GFLOPS | Progress: (10/10) | 2.74 s Done. [Task 12/25]  Current/Best:   96.48/ 294.40 GFLOPS | Progress: (10/10) | 2.82 s Done. [Task 13/25]  Current/Best:  123.74/ 354.34 GFLOPS | Progress: (10/10) | 2.62 s Done. [Task 14/25]  Current/Best:   23.76/ 178.71 GFLOPS | Progress: (10/10) | 2.90 s Done. [Task 15/25]  Current/Best:  119.18/ 534.63 GFLOPS | Progress: (10/10) | 2.49 s Done. [Task 16/25]  Current/Best:  101.24/ 172.92 GFLOPS | Progress: (10/10) | 2.49 s Done. [Task 17/25]  Current/Best:  309.85/ 309.85 GFLOPS | Progress: (10/10) | 2.69 s Done. [Task 18/25]  Current/Best:   54.45/ 368.31 GFLOPS | Progress: (10/10) | 2.46 s Done. [Task 19/25]  Current/Best:   78.69/ 162.43 GFLOPS | Progress: (10/10) | 3.29 s Done. [Task 20/25]  Current/Best:   40.78/ 317.50 GFLOPS | Progress: (10/10) | 4.52 s Done. [Task 21/25]  Current/Best:  169.03/ 296.36 GFLOPS | Progress: (10/10) | 3.95 s Done. [Task 22/25]  Current/Best:   90.96/ 210.43 GFLOPS | Progress: (10/10) | 2.28 s Done. [Task 23/25]  Current/Best:   48.93/ 217.36 GFLOPS | Progress: (10/10) | 2.87 s Done. [Task 25/25]  Current/Best:    0.00/   0.00 GFLOPS | Progress: (0/10) | 0.00 s Done. [Task 25/25]  Current/Best:   25.50/  33.86 GFLOPS | Progress: (10/10) | 9.28 s Done. ## Compiling an Optimized Model with Tuning Data class="n02123045 tabby, tabby cat" with probability=0.621104 class="n02123159 tiger cat" with probability=0.356378 class="n02124075 Egyptian cat" with probability=0.019712 class="n02129604 tiger, Panthera tigris" with probability=0.001215 class="n04040759 radiator" with probability=0.000262 ## Comparing the Tuned and Untuned Models optimized: {"mean": 34.736288779822644, "median": 34.547542000655085, "std": 0.5144378649382363} unoptimized: {"mean": 44.97057118016528, "median": 42.52320024970686, "std": 6.870915251002107}  real    3m23.904s user    5m2.900s sys     5m37.099s
  对比性能数据,可以发现:调优模型的运行速度更快、更平稳。 参考笔记:  start-ai-compiler[7] 资料: 2020 / The Deep Learning Compiler: A Comprehensive Survey[8] [译] 深度学习编译器综述[9] 2018 / TVM: An Automated End-to-End Optimizing Compiler for Deep Learning[10] [译] TVM: 一个自动的端到端深度学习优化编译器[11] 脚注
  [1] Design and Architecture:  https://tvm.apache.org/docs/arch/index.html
  [2] User Tutorial:  https://tvm.apache.org/docs/tutorial/index.html
  [3] Compiling and Optimizing a Model with the Python Interface (AutoTVM):  https://tvm.apache.org/docs/tutorial/autotvm_relay_x86.html
  [4] Installing TVM:  https://tvm.apache.org/docs/tutorial/install.html
  [5]「TVM 安装」:  https://github.com/ikuokuo/start-ai-compiler/blob/main/docs/tvm/tvm_install.md
  [6] Intel  Products:  https://www.intel.com/content/www/us/en/products/overview.html
  [7] start-ai-compiler:  https://github.com/ikuokuo/start-ai-compiler#%E7%AC%94%E8%AE%B0
  [8] 2020 / The Deep Learning Compiler: A Comprehensive Survey:  https://arxiv.org/abs/2002.03794
  [9] [译] 深度学习编译器综述:  https://www.jianshu.com/p/ed372af7ef09
  [10] 2018 / TVM: An Automated End-to-End Optimizing Compiler for Deep Learning:  https://www.usenix.org/conference/osdi18/presentation/chen
  [11] [译] TVM: 一个自动的端到端深度学习优化编译器:  https://zhuanlan.zhihu.com/p/426994569

美团联名信用卡上线3周年成绩单累计发卡突破1500万张本报记者李冰近日,国内十余家区域银行携手美团共同发起美团联名卡上线三周年消费回馈活动。综合多家银行反馈的信息,截至目前,美团与全国多地区域银行联合推出的美团联名信用卡累计发卡已突破小白前端,带你一起学习前端开发holle朋友们大家好!这是第一次与大家接触,本人是一名工作一年多的前端开发工程师,希望以后的日子能与大家一起学习前端开发,能在钻研技术的道路上越走越远。总所周知大部分的编程语言都长期投资巴菲特入股比亚迪始末迪历distory系列专栏之一时间回到2008年,彼时全球金融风暴肆虐,股权投资不断萎缩。2008年7月底,巴菲特旗下的中美能源公司总裁索科尔前往比亚迪深圳总部参观考察。回到美国后鼓励企业建设跨境电商独立站南都讯记者陈盈珊跨境电商风往哪吹?自建独立站打造龙头企业,建立行业话语权,成为共识。日前,广东省人民政府办公厅印发关于推进跨境电商高质量发展若干政策措施的通知。当中,特别提及建立跨华为麒麟处理器,哪几款比较经典,具有里程碑的意义?文小伊评科技在华为被制裁之后,最可惜的莫过于麒麟芯片了,因为华为麒麟芯片自从麒麟980时代开始,就已经踏上了快车道,明显可以感觉华为海思对于麒麟处理器的打磨更加的纯熟。如果华为不被目前用的荣耀30pro纠结换不换VIVOX60,两款手机的区别是什么?看到很多人都说荣耀30Pro没必要换,想想也正常,毕竟这手机才出来一年,用一年就换明显太浪费了。但我想说在座的各位都没get到题主荣耀30Pro换vivoX60的精髓!第一点相比荣2000元左右的5G手机有什么推荐吗?目前2000元左右的5G手机还是比较多,但是性价比高的,个人认为只有两款,其他机型性价比都太低了。为什么只有两款?因为搭载麒麟820处理器的手机目前只有两款。2000元价位首要的就放在钱包里的迷你手机,长得和卡片一样,体验像是会打电话的玩具拒绝参数,只谈体验,关注导盲犬小扣,真实解读您熟悉的数码产品,本文阅读预计耗时3分钟。手机发展到今天,其智能化程度越来越高,也越来越朝着万物互联的方向前进。大的主流不变,小的旁支却到2025年,山东基本建成制造强省每年组织实施100项重大科技创新项目12月10日上午,山东省政府新闻办召开山东制造业高质量发展专题新闻发布会,这是本年度第200场省级新闻发布会。由此,山东也成为全国首个年度发布会场次突破200场的省份。据悉,山东将融资丨脉流科技完成近亿元B轮融资,深入心脑血管智能诊疗领域创业邦获悉,心脑血管疾病智能诊疗领跑者脉流科技完成近亿元B轮融资。脉流科技创始人兼CEO向建平博士表示,本轮资金将用于公司心脑血管疾病功能学评估产品的进一步商业化推广和落地,扩充市未来想从事人工智能领域,本科数学专业与计算机专业选哪个比较好呢?人工智能是我的主要研究方向之一,我也是一名计算机专业的研究生导师,所以我来回答一下这个问题。数学专业和计算机专业都与人工智能关系密切,目前有的高校已经把数学专业并入到信息学院,所以
Canalys2021年中国个人电脑市场出货量增长1036氪获悉,据市场研究机构Canalys发布的最新报告指出,2021年第四季度,中国个人电脑出货量(不含平板电脑)增长9,达到1650万台。整体来看,2021年中国市场全年出货量增国际最新研究全球天文科研设备碳排放每年至少120万吨中新网北京3月22日电(记者孙自法)施普林格自然旗下专业学术期刊自然天文学最新发表的一篇论文估计,全球空间和地基科研设备是天文学研究碳足迹的最大贡献者,其年均温室气体排放量相当于每中国工程院院士张平6G通信指标相比5G将有10中国工程院院士张平6G通信指标相比5G将有10100倍提升财联社3月22日电,中国工程院院士北京邮电大学教授张平在今日举行的全球6G技术大会上表示,6G的通信指标相比5G将有101雷蛇发布2米长雷电4数据线尼龙编织线材,899元IT之家3月20日消息,雷蛇现已发布新款雷蛇雷电4数据线,最长可选2m,售价899元。据介绍,雷蛇新款雷电4数据线可以提供40bps的数据传输速度可进行最高8K分辨率的图像传输,还蔚来资本宣布完成约4亿美元二期基金募集及人民币二期基金首关品玩3月21日讯,蔚来资本发布公告称,已关闭第二期美元基金(NIOCapitalEveONEFundIIL。P。,以下简称基金)的募资,本期基金规模约4亿美元,规模是美元一期基金的iPhone14惊艳渲染图曝光,iPhone13价比老人机刷新爱疯纪录近日,爆料人xleaks7(大卫科瓦尔斯基)曝光了一组iPhone14Pro渲染图,我们可以看到该机的屏幕采用了挖孔设计,前置摄像头和FaceID组件分别放置,从类似于感叹号。与刘咋挑家用路由器先来简单的说首先,路由器不是天线越多越好,还得看具体的参数,不要被那一堆天线迷惑其次,无论是百兆路由还是千兆路由,这是说的网速,并不代表远近最后,还是要选一个信得过的品牌,想在烂苹红米新一款高性价比手机产品,千元买6000毫安大电池,香不香在红米k50发布之后是,本来以为现在在市场上的5G网络手机产品中,红米k50这款产品的会以红米现阶段市场最大电池手机产品,在市场上发展上一段不短的时间,但是没有想到,红米这么快就带算一算苹果的芯片成本,卖贵了?来源内容由半导体行业观察(IDicbank)编译自medium,谢谢。苹果公司是计算机行业的一个传奇!但是它的价格是昂贵的!在本文里,我们将通过分析其用组件价格,来分析一下其成本。国家级科技企业孵化器迎来新一轮扩容来源经济参考报作为国家双创工作重要抓手的国家级科技企业孵化器迎来新一轮扩容。科技部火炬中心日前正式公示2021年度拟备案为国家级科技企业孵化器名单,包括北京创E新一代信息技术产业孵数据即产品,数据团队如何不再做表哥表姐?随着数字化转型的不断深入,快速攀升的数据量级以及多样化的数据分析需求导致企业的数据架构日益复杂,与此同时,后期的运维难度和运维成本也在不断上升。现在一套数据架构上往往存在多个不同功