3

新手问题。我一直在尝试将这个 PyTorch 模型转换为 CoreML 模型。我已按照此处的指南进行操作,但无法使其正常工作。我尝试了跟踪和编写脚本,但遇到的错误提示可能存在 TorchScript 不支持的操作:

错误torch.jit.traceRuntimeError: PyTorch convert function for op 'pythonop' not implemented

错误torch.jit.scriptRuntimeError: Python builtin <built-in method apply of FunctionMeta object at 0x7fa37e2ad600> is currently not supported in Torchscript

我怀疑可能无法将任何 PyTorch 模型转换为 CoreML 模型。是这样吗?我可以在不深入研究 PyTorch 操作和层的情况下以某种方式克服错误吗?

我的python脚本以防万一(模型在本地加载):

import warnings
import torch
import torch.nn as nn
import coremltools as ct

from efficientnet_pytorch import EfficientNet
from torchvision import datasets, models, transforms
from PIL import Image

# Simple loading the model
# model = torch.load('food308_efnetb2_91.31.pth', map_location=torch.device('cpu')) 
# ends up with RuntimeError("Could not get name of python class object")

# Load the model
model = EfficientNet.from_pretrained('efficientnet-b2')
num_ftrs = model._fc.in_features
model._fc = nn.Linear(num_ftrs, 308)
prev_state = torch.load('food308_efnetb2_91.31.pth', map_location=torch.device('cpu'))
model.load_state_dict(prev_state)
model.eval()

# Model tracing
example_input = torch.rand(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)
mlmodel = ct.convert(
    traced_model,
    inputs=[ct.TensorType(name="input", shape=(1, 3, 64, 64))],
)

# Model scripting
scripted_model = torch.jit.script(model)
mlmodel2 = ct.convert(
    scripted_model,
    inputs=[ct.TensorType(name="input", shape=(1, 3, 64, 64))],
)
4

0 回答 0