pytorch模型转换问题记录

博主遇到在开发板上加载PyTorch模型的问题,错误提示为'filenotfound:archive/constants.pkl'。解决方案是将模型转换为TorchScript格式以便跨脚本使用。通过torch.jit.trace将模型转换并保存,解决了直接使用torch.save()导致的加载问题。此外,注意在forward函数中避免将tensor转换为Python数值,以防止TracerWarning。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题1:file not found: archive/constants.pkl

为了在开发板上使用模型,我用转换脚本加载了我生成的pytorch模型文件,但是却报错了。就是标题的信息。

经过搜索,这里有相关解释和解决方法:
https://developer.qualcomm.com/sites/default/files/docs/snpe/model_conv_pytorch.html
https://pytorch.org/tutorials/advanced/cpp_export.html#converting-to-torch-script-via-tracing

简单来说,原因就是我保存模型直接用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就没问题了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值