一文詳解如何實(shí)現(xiàn)PyTorch模型編譯
準(zhǔn)備
本篇文章譯自英文文檔 Compile PyTorch Models。
作者是 Alex Wong。
更多 TVM 中文文檔可訪問 →TVM 中文站。
本文介紹了如何用 Relay 部署 PyTorch 模型。
首先應(yīng)安裝 PyTorch。此外,還應(yīng)安裝 TorchVision,并將其作為模型合集 (model zoo)。
可通過 pip 快速安裝:
pip install torch==1.7.0 pip install torchvision==0.8.1
或參考官網(wǎng):pytorch.org/get-started…
PyTorch 版本應(yīng)該和 TorchVision 版本兼容。
目前 TVM 支持 PyTorch 1.7 和 1.4,其他版本可能不穩(wěn)定。
import tvm from tvm import relay import numpy as np from tvm.contrib.download import download_testdata # 導(dǎo)入 PyTorch import torch import torchvision
加載預(yù)訓(xùn)練的 PyTorch 模型?
model_name = "resnet18" model = getattr(torchvision.models, model_name)(pretrained=True) model = model.eval() # 通過追蹤獲取 TorchScripted 模型 input_shape = [1, 3, 224, 224] input_data = torch.randn(input_shape) scripted_model = torch.jit.trace(model, input_data).eval() 輸出結(jié)果:
Downloading: "download.pytorch.org/models/resn…" to /workspace/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth
0%| | 0.00/44.7M [00:00<?, ?B/s] 11%|# | 4.87M/44.7M [00:00<00:00, 51.0MB/s] 22%|##1 | 9.73M/44.7M [00:00<00:00, 49.2MB/s] 74%|#######3 | 32.9M/44.7M [00:00<00:00, 136MB/s] 100%|##########| 44.7M/44.7M [00:00<00:00, 129MB/s]
加載測試圖像?
經(jīng)典的貓咪示例:
from PIL import Image img_url = "https://github.com/dmlc/mxnet.js/blob/main/data/cat.png?raw=true" img_path = download_testdata(img_url, "cat.png", module="data") img = Image.open(img_path).resize((224, 224)) # 預(yù)處理圖像,并將其轉(zhuǎn)換為張量 from torchvision import transforms my_preprocess = transforms.Compose( [ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ] ) img = my_preprocess(img) img = np.expand_dims(img, 0)
將計(jì)算圖導(dǎo)入 Relay?
將 PyTorch 計(jì)算圖轉(zhuǎn)換為 Relay 計(jì)算圖。input_name 可以是任意值。
input_name = "input0" shape_list = [(input_name, img.shape)] mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)
Relay 構(gòu)建?
用給定的輸入規(guī)范,將計(jì)算圖編譯為 llvm target。
target = tvm.target.Target("llvm", host="llvm") dev = tvm.cpu(0) with tvm.transform.PassContext(opt_level=3): lib = relay.build(mod, target=target, params=params)
輸出結(jié)果:
/workspace/python/tvm/driver/build_module.py:268: UserWarning: target_host parameter is going to be deprecated. Please pass in tvm.target.Target(target, host=target_host) instead.
"target_host parameter is going to be deprecated. "
在 TVM 上執(zhí)行可移植計(jì)算圖?
將編譯好的模型部署到 target 上:
from tvm.contrib import graph_executor dtype = "float32" m = graph_executor.GraphModule(lib["default"](dev)) # 設(shè)置輸入 m.set_input(input_name, tvm.nd.array(img.astype(dtype))) # 執(zhí)行 m.run() # 得到輸出 tvm_output = m.get_output(0)
查找分類集名稱?
在 1000 個類的分類集中,查找分?jǐn)?shù)最高的第一個:
synset_url = "".join( [ "https://raw.githubusercontent.com/Cadene/", "pretrained-models.pytorch/master/data/", "imagenet_synsets.txt", ] ) synset_name = "imagenet_synsets.txt" synset_path = download_testdata(synset_url, synset_name, module="data") with open(synset_path) as f: synsets = f.readlines() synsets = [x.strip() for x in synsets] splits = [line.split(" ") for line in synsets] key_to_classname = {spl[0]: " ".join(spl[1:]) for spl in splits} class_url = "".join( [ "https://raw.githubusercontent.com/Cadene/", "pretrained-models.pytorch/master/data/", "imagenet_classes.txt", ] ) class_name = "imagenet_classes.txt" class_path = download_testdata(class_url, class_name, module="data") with open(class_path) as f: class_id_to_key = f.readlines() class_id_to_key = [x.strip() for x in class_id_to_key] # 獲得 TVM 的前 1 個結(jié)果 top1_tvm = np.argmax(tvm_output.numpy()[0]) tvm_class_key = class_id_to_key[top1_tvm] # 將輸入轉(zhuǎn)換為 PyTorch 變量,并獲取 PyTorch 結(jié)果進(jìn)行比較 with torch.no_grad(): torch_img = torch.from_numpy(img) output = model(torch_img) # 獲得 PyTorch 的前 1 個結(jié)果 top1_torch = np.argmax(output.numpy()) torch_class_key = class_id_to_key[top1_torch] print("Relay top-1 id: {}, class name: {}".format(top1_tvm, key_to_classname[tvm_class_key])) print("Torch top-1 id: {}, class name: {}".format(top1_torch, key_to_classname[torch_class_key]))
輸出結(jié)果:
Relay top-1 id: 281, class name: tabby, tabby cat
Torch top-1 id: 281, class name: tabby, tabby cat
下載 Jupyter Notebook:from_pytorch.ipynb
以上就是一文詳解如何實(shí)現(xiàn)PyTorch 模型編譯 的詳細(xì)內(nèi)容,更多關(guān)于PyTorch 模型編譯 的資料請關(guān)注腳本之家其它相關(guān)文章!
- 詳解使用Pytorch Geometric實(shí)現(xiàn)GraphSAGE模型
- PyTorch模型轉(zhuǎn)換為ONNX格式實(shí)現(xiàn)過程詳解
- 利用Pytorch實(shí)現(xiàn)ResNet網(wǎng)絡(luò)構(gòu)建及模型訓(xùn)練
- 詳解利用Pytorch實(shí)現(xiàn)ResNet網(wǎng)絡(luò)之評估訓(xùn)練模型
- pytorch模型的保存加載與續(xù)訓(xùn)練詳解
- AMP?Tensor?Cores節(jié)省內(nèi)存PyTorch模型詳解
- 詳解?PyTorch?Lightning模型部署到生產(chǎn)服務(wù)中
- Pytorch模型定義與深度學(xué)習(xí)自查手冊
相關(guān)文章
Django如何實(shí)現(xiàn)網(wǎng)站注冊用戶郵箱驗(yàn)證功能
這篇文章主要介紹了Django如何實(shí)現(xiàn)網(wǎng)站注冊用戶郵箱驗(yàn)證功能,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08520使用Python實(shí)現(xiàn)“我愛你”表白
這篇文章主要介紹了520使用Python實(shí)現(xiàn)“我愛你”表白,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05python析構(gòu)函數(shù)用法及注意事項(xiàng)
在本篇文章里小編給大家整理的是一篇關(guān)于python析構(gòu)函數(shù)用法及注意事項(xiàng),有需要的朋友們可以學(xué)習(xí)參考下。2021-06-06Python實(shí)現(xiàn)生成簡單的Makefile文件代碼示例
這篇文章主要介紹了Python實(shí)現(xiàn)生成簡單的Makefile文件代碼示例,本文給出了兩段實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-03-03基于Python實(shí)現(xiàn)地標(biāo)景點(diǎn)識別功能
地標(biāo)景點(diǎn)識別是一種基于計(jì)算機(jī)視覺技術(shù)的應(yīng)用,旨在通過對圖像進(jìn)行分析和處理,自動識別出圖片中的地標(biāo)景點(diǎn),本文將介紹地標(biāo)景點(diǎn)識別的背景和原理,并使用Python編程語言來實(shí)現(xiàn)一個簡單的地標(biāo)景點(diǎn)識別系統(tǒng),感興趣的朋友可以參考下2024-01-01Python?中的?Counter?模塊及使用詳解(搞定重復(fù)計(jì)數(shù))
Counter 是一個簡單的計(jì)數(shù)器,用于統(tǒng)計(jì)某些可哈希對象的數(shù)量。它以字典的形式存儲元素和它們的計(jì)數(shù),這篇文章主要介紹了Python?中的?Counter?模塊及使用詳解(搞定重復(fù)計(jì)數(shù)),需要的朋友可以參考下2023-04-04