pytorch模型转换问题记录
问题1:file not found: archive/constants.pkl
为了在开发板上使用模型,我用转换脚本加载了我生成的pytorch模型文件,但是却报错了。就是标题的信息。
经过搜索,这里有相关解释和解决方法:
简单来说,原因就是我保存模型直接用torch.save(), 没法在其它脚本中直接加载,除非那个脚本中也有nn.Module子类的定义。 我需要把我的模型保存为TorchScript格式。具体方法就是使用
trace_model = torch.jit.trace(net, (torch.Tensor(1,256), torch.Tensor(1,256))) //这里有两个输入tensor modelfile = ./test.pt trace_model.save(modelfile)
这样保存的pt就可以在其它python里加载了。
问题2:TracerWarning: Converting a tensor to a Python number might cause the trace to be incorrect. We can’t record the data flow of Python values, so this value will be treated as a constant in the future.
我在forward()函数里把tensor转换为python数值来显示,调用torch.jit.trace就会报错。在forward()函数里所有的操作都用tensor就没问题了。