问题1:
RuntimeError:
Could not export Python function call 'Detect'. Remove calls to Python functions before export. Did you forget add @script or @script_method annotation? If this is a nn.ModuleList, add it to __constants__
字面解释:无法导出“Detect”函数,需要将其移除
解决方式:后处理过程无法被torch.jit.trace跟踪
①将后处理过程(Detect、NMS等,具体看报错的是哪个函数)从网络的forward函数中移出,可以将后处理过程单独定义一个函数,模型推理完再调用该函数进行后处理;
②检查模型导入时的设置,有些模型训练和测试调用的forward函数不同,导入模型时只需将相关参数设置成训练即可,以ssd.pytorch为例
net = build_ssd('test', 300, num_classes)#这样调用ssd模型,forward函数会调用detect后处理
只需将“test”改为“train”即可解决上述问题
问题2:[ CPUFloatType{8732,4} ]) of traced region did not have observable data dependence with trace inputs; this probably indicates your program cannot be understood by the tracer.
解决方式:检查模型forward函数的返回值是否为Tensor
像上述ssd返回的就是一个list,可以查看这几个元素的维度
可以对self.priors使用torch.unsqueeze升维为[1,8732,4],然后再利用torch.cat对这三个元素进行拼接,具体如下:
output = torch.cat(
(loc.view(loc.size(0), -1, 4),
conf.view(conf.size(0), -1, self.num_classes),
torch.unsqueeze(self.priors)), dim=2)
这样ssd推理就返回了一个tensor,后续可以采用切片操作对推理结果进行后处理,具体如下:
#后处理部分
softmax = nn.Softmax()
loc_prd = results[:,:,0:4]
conf_preds = softmax(torch.squeeze(results[:,:,4:25]))
default_boxes = torch.squeeze(results[:,:,25:29]).type(type(x.data))
post_process = Detect()
detections = post_process.apply(21, 0, 200, 0.01, 0.45, loc_prd, conf_preds, default_boxes)