背景:
使用vs2017编写加载mnn模型并推理输入图片的程序,发生如下错误
The 321's input is not ready
Resize error for 321, code=3
Resize error for ConvertTensor3, code=3
Can't run session because not resized
由于一开始在linux下生成的项目可执行文件也报了这个错误输出,其他推理的输出也是正常的;根据https://github.com/alibaba/MNN/issues/107
的回答还以为没什么事,但换到windows下使用同样的代码在vs中执行同样的任务时候
linux下运行可执行文件的输出:
The 321's input is not ready
Resize error for [Convolution], 321, code=3
尝试(无效):
1.查看了大量的使用函数的源代码,找到报错信息输出的函数内参数的变化;
2.另外还是用了逐步debug到函数内部,但这种方式不能追溯到dll中封装好的函数;
3.也同时尝试了不同版本的visual stuido
4.试了不同的mnn模型,但都是onnx生成的
解决:
出错的问题是因为在根据以下网址https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html
将pytorch模型转为onnx模型时,直接使用了例子中的export函数的全部内容,即全部参数,但根据https://github.com/alibaba/MNN/issues/463
上作者的回答,在vs读取mnn模型推理时(即runtime)需要fix input shape,而以下生成onnx模型的代码中的dynamic_axes
把模型输入的batchsize改成了不定项,所以得到的onnx,mnn模型的输入尺寸均不定,即使在vs加入下列代码也没有用,因为已经在c++里用的时候已经是runtime,不支持runtime的resize。
interpreter->resizeTensor(input_tensor, input_dims);
interpreter->resizeSession(ultraview_session);
生成onnx模型的代码
# Input to the model
x = torch.randn(1, 1, 224, 224)
torch_out = torch_model(x)
# Export the model
torch.onnx.export(torch_model, # model being run
x, # model input (or a tuple for multiple inputs)
"super_resolution.onnx", # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=10, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['input'], # the model's input names
output_names = ['output'], # the model's output names
dynamic_axes={'input' : {0 : 'batch_size'}, # variable lenght axes
'output' : {0 : 'batch_size'}})