背景:
使用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'}})