将Pytorch模型加载到C++;使用Dev-Pytorch 1.0 PyRo火炬1具有将模型转换成一个TARK脚本程序(以某种方式串行化)的功能,以使其在C++中执行而不需要Python依赖。p>

将Pytorch模型加载到C++;使用Dev-Pytorch 1.0 PyRo火炬1具有将模型转换成一个TARK脚本程序(以某种方式串行化)的功能,以使其在C++中执行而不需要Python依赖。p>,pytorch,Pytorch,有关详细信息,请参见本教程。 这是如何做到的: import torch import torchvision # An instance of your model. model = A UNET MODEL FROM FASTAI which has hooks as required by UNET # An example input you would normally provide to your model's forward() method. example = tor

有关详细信息,请参见本教程。

这是如何做到的:

import torch
import torchvision

# An instance of your model.
model = A UNET MODEL FROM FASTAI which has hooks as required by UNET

# An example input you would normally provide to your model's forward() method.
example = torch.rand(1, 3, 224, 224)

# Use torch.jit.trace to generate a torch.jit.ScriptModule via tracing.
traced_script_module = torch.jit.trace(model, example)
在我的用例中,我使用一个UNET模型进行语义分割。但是,我使用此方法跟踪模型,得到以下错误

Forward or backward hooks can't be compiled 

UNET模型使用钩子来保存中间特征,这些特征在网络的后续层中使用。有办法绕过它吗?或者,这仍然是这种新方法的一个局限性,即它无法使用这种挂钩处理模型

> P>你可以改写C++中的模型,因为C++ API与Python版本的接口几乎相同。它将与TorchScript一起工作

import torch

# downloading the model from torchhub
model = torch.hub.load('mateuszbuda/brain-segmentation-pytorch', 'unet',
    in_channels=3, out_channels=1, init_features=32, pretrained=True)

#  downloading the sample
import urllib
url, filename = ("https://github.com/mateuszbuda/brain-segmentation-pytorch/raw/master/assets/TCGA_CS_4944.png", "TCGA_CS_4944.png")
try: urllib.URLopener().retrieve(url, filename)
except: urllib.request.urlretrieve(url, filename)
    
# reading the sample and some prerequisites for transformation
import numpy as np
from PIL import Image
from torchvision import transforms

input_image = Image.open(filename)

m, s = np.mean(input_image, axis=(0, 1)), np.std(input_image, axis=(0, 1))
preprocess = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean=m, std=s),])

input_tensor = preprocess(input_image)

input_batch = input_tensor.unsqueeze(0)

# creating the trace
traced_module = torch.jit.trace(model,input_batch)

# running the trace
traced_module(input_batch)

PS:Tr.jt.Trace/Trj.jist.Script不支持所有的火箭弹功能,所以使用外部库总是很棘手。

我想使用PyTrac来实现我的模型,然后将其加载到C++中,尽管我没有找到足够的DOC。如果你能分享你的经验,我将不胜感激。比如你是如何解决上面这个问题的?您是否发现装载过程非常不同…等等。