編譯 PyTorch 模型

超神經HyperAI發表於2023-04-29

本篇文章譯自英文檔案 Compile PyTorch Models

作者是 Alex Wong

更多 TVM 中文檔案可訪問 →TVM 中文站

本文介紹瞭如何用 Relay 部署 PyTorch 模型。

首先應安裝 PyTorch。此外,還應安裝 TorchVision,並將其作為模型合集 (model zoo)。

可透過 pip 快速安裝:

pip install torch==1.7.0
pip install torchvision==0.8.1

或參考官網:https://pytorch.org/get-started/locally/

PyTorch 版本應該和 TorchVision 版本相容。

目前 TVM 支援 PyTorch 1.7 和 1.4,其他版本可能不穩定。

import tvm
from tvm import relay

import numpy as np

from tvm.contrib.download import download_testdata

# 匯入 PyTorch
import torch
import torchvision

載入預訓練的 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()
輸出結果:

Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" 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]

載入測試影像​

經典的貓咪示例:

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))

# 預處理影像,並將其轉換為張量
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)

將計算圖匯入 Relay​

將 PyTorch 計算圖轉換為 Relay 計算圖。input_name 可以是任意值。

input_name = "input0"
shape_list = [(input_name, img.shape)]
mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)

Relay 構建​

用給定的輸入規範,將計算圖編譯為 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)

輸出結果:

/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 上執行可移植計算圖​

將編譯好的模型部署到 target 上:

from tvm.contrib import graph_executor

dtype = "float32"
m = graph_executor.GraphModule(lib["default"](dev))
# 設定輸入
m.set_input(input_name, tvm.nd.array(img.astype(dtype)))
# 執行
m.run()
# 得到輸出
tvm_output = m.get_output(0)

查詢分類集名稱​

在 1000 個類的分類集中,查詢分數最高的第一個:

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 個結果
top1_tvm = np.argmax(tvm_output.numpy()[0])
tvm_class_key = class_id_to_key[top1_tvm]

# 將輸入轉換為 PyTorch 變數,並獲取 PyTorch 結果進行比較
with torch.no_grad():
    torch_img = torch.from_numpy(img)
    output = model(torch_img)

 # 獲得 PyTorch 的前 1 個結果
    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]))

輸出結果:

Relay top-1 id: 281, class name: tabby, tabby cat
Torch top-1 id: 281, class name: tabby, tabby cat

下載 Python 原始碼:from_pytorch.py

下載 Jupyter Notebook:from_pytorch.ipynb

相關文章