我已经在PyTorch中训练了一个VAE,我需要将其转换为CoreML。通过该线程PyTorch VAE fails conversion to onnx,我可以导出ONNX模型,但是,这仅将问题推到了ONNX-CoreML阶段。
包含torch.randn()
调用的原始函数是重新参数化函数:
def reparametrize(self, mu, logvar):
std = logvar.mul(0.5).exp_()
if self.have_cuda:
eps = torch.randn(self.bs, self.nz, device='cuda')
else:
eps = torch.randn(self.bs, self.nz)
return eps.mul(std).add_(mu)
解决方案当然是创建自定义图层,但是在创建没有输入的图层时遇到问题(即,它只是一个randn()
调用)。
我可以通过以下定义完成CoreML转换:
def convert_randn(node):
params = NeuralNetwork_pb2.CustomLayerParams()
params.className = "RandomNormal"
params.description = "Random normal distribution generator"
params.parameters["dtype"].intValue = node.attrs.get('dtype', 1)
params.parameters["bs"].intValue = node.attrs.get("shape")[0]
params.parameters["nz"].intValue = node.attrs.get("shape")[1]
return params
我通过以下方式进行转换:
coreml_model = convert(onnx_model, add_custom_layers=True,
image_input_names = ['input'],
custom_conversion_functions={"RandomNormal": convert_randn})
我还应注意,mlmodel
导出完成后,将打印以下内容:
Custom layers have been added to the CoreML model corresponding to the
following ops in the onnx model:
1/1: op type: RandomNormal, op input names and shapes: [], op output
names and shapes: [('62', 'Shape not available')]
将.mlmodel
引入Xcode抱怨Layer '62' of type 500 has 0 inputs but expects at least 1.
,所以我想知道如何为图层指定一种“虚拟”输入,因为它实际上没有输入-它是只是torch.randn()
(或更具体地说,onnx RandonNormal
op)的包装。我需要澄清的是,我确实需要整个VAE,而不仅仅是解码器,因为我实际上是在使用整个过程来“纠错”我的输入(即,编码器根据输入来估算我的z
矢量) ,然后解码器会生成最接近的输入通用化预测。
任何帮助,我们将不胜感激。
更新:好的,我终于在Xcode中加载了一个版本(感谢@MattijsHollemans和他的书!)。 originalConversion.mlmodel
是将模型从ONNX转换为CoreML的初始输出。为此,我必须手动插入RandomNormal
层的输入。我无缘无故地做到了(64,28,28)—我知道我的批处理大小是64,我的输入是28 x 28(但也可能是(1、1、1、1),因为它是“虚拟的” ”):
spec = coremltools.utils.load_spec('originalConversion.mlmodel')
nn = spec.neuralNetwork
layers = {l.name:i for i,l in enumerate(nn.layers)}
layer_idx = layers["62"] # '62' is the name of the layer -- see above
layer = nn.layers[layer_idx]
layer.input.extend(["dummy_input"])
inp = spec.description.input.add()
inp.name = "dummy_input"
inp.type.multiArrayType.SetInParent()
spec.description.input[1].type.multiArrayType.shape.append(64)
spec.description.input[1].type.multiArrayType.shape.append(28)
spec.description.input[1].type.multiArrayType.shape.append(28)
spec.description.input[1].type.multiArrayType.dataType = ft.ArrayFeatureType.DOUBLE
coremltools.utils.save_spec(spec, "modelWithInsertedInput.mlmodel")
这将在Xcode中加载,但是我尚未在我的应用中测试模型的功能。由于附加层很简单,并且输入实际上是伪造的,非功能性的输入(只是为了让Xcode开心),我不认为这会是一个问题,但是如果 doesn 't 正常运行。
更新2:不幸的是,该模型无法在运行时加载。由于[espresso] [Espresso::handle_ex_plan] exception=Failed in 2nd reshape after missing custom layer info.
失败,我发现非常奇怪而令人困惑,是检查model.espresso.shape
时,我发现几乎每个节点都具有如下形状:
"62" : {
"k" : 0,
"w" : 0,
"n" : 0,
"seq" : 0,
"h" : 0
}
我有两个问题/担忧:1)最明显的是,为什么所有值都为零(除了输入节点以外的所有情况都是如此),以及2)为什么当它只是一个顺序模型时相当常规的VAE?在同一应用中打开model.espresso.shape
以使用功能齐全的GAN,我发现节点的格式为:
"54" : {
"k" : 256,
"w" : 16,
"n" : 1,
"h" : 16
}
也就是说,它们包含合理的形状信息,并且没有具有seq
字段。
非常非常困惑...
更新3:我也刚刚在编译器报告中注意到错误:IMPORTANT: new sequence length computation failed, falling back to old path. Your compilation was sucessful, but please file a radar on Core ML | Neural Networks and attach the model that generated this message.
这是原始的PyTorch模型:
class VAE(nn.Module):
def __init__(self, bs, nz):
super(VAE, self).__init__()
self.nz = nz
self.bs = bs
self.encoder = nn.Sequential(
# input is (nc) x 28 x 28
nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),
nn.LeakyReLU(0.2, inplace=True),
# size = (ndf) x 14 x 14
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True),
# size = (ndf*2) x 7 x 7
nn.Conv2d(ndf * 2, ndf * 4, 3, 2, 1, bias=False),
nn.BatchNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True),
# size = (ndf*4) x 4 x 4
nn.Conv2d(ndf * 4, 1024, 4, 1, 0, bias=False),
nn.LeakyReLU(0.2, inplace=True),
)
self.decoder = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d( 1024, ngf * 8, 4, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 8),
nn.ReLU(True),
# size = (ngf*8) x 4 x 4
nn.ConvTranspose2d(ngf * 8, ngf * 4, 3, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
# size = (ngf*4) x 8 x 8
nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
# size = (ngf*2) x 16 x 16
nn.ConvTranspose2d(ngf * 2, nc, 4, 2, 1, bias=False),
nn.Sigmoid()
)
self.fc1 = nn.Linear(1024, 512)
self.fc21 = nn.Linear(512, nz)
self.fc22 = nn.Linear(512, nz)
self.fc3 = nn.Linear(nz, 512)
self.fc4 = nn.Linear(512, 1024)
self.lrelu = nn.LeakyReLU()
self.relu = nn.ReLU()
def encode(self, x):
conv = self.encoder(x);
h1 = self.fc1(conv.view(-1, 1024))
return self.fc21(h1), self.fc22(h1)
def decode(self, z):
h3 = self.relu(self.fc3(z))
deconv_input = self.fc4(h3)
deconv_input = deconv_input.view(-1,1024,1,1)
return self.decoder(deconv_input)
def reparametrize(self, mu, logvar):
std = logvar.mul(0.5).exp_()
eps = torch.randn(self.bs, self.nz, device='cuda') # needs custom layer!
return eps.mul(std).add_(mu)
def forward(self, x):
# print("x", x.size())
mu, logvar = self.encode(x)
z = self.reparametrize(mu, logvar)
decoded = self.decode(z)
return decoded, mu, logvar
答案 0 :(得分:1)
要向您的Core ML模型添加输入,可以从Python执行以下操作:
import coremltools
spec = coremltools.utils.load_spec("YourModel.mlmodel")
nn = spec.neuralNetworkClassifier # or just spec.neuralNetwork
layers = {l.name:i for i,l in enumerate(nn.layers)}
layer_idx = layers["your_custom_layer"]
layer = nn.layers[layer_idx]
layer.input.extend(["dummy_input"])
inp = spec.description.input.add()
inp.name = "dummy_input"
inp.type.doubleType.SetInParent()
coremltools.utils.save_spec(spec, "NewModel.mlmodel")
在这里,"your_custom_layer"
是要将虚拟输入添加到的图层的名称。在您的模型中,它看起来像是62
。您可以查看layers
词典以查看模型中所有图层的名称。
注意:
nn = spec.neuralNetwork
代替neuralNetworkClassifier
。