pytorch导出torchscript记录

本文详细记录了在使用PyTorch的TorchScript导出PatchmatchNet模型时遇到的各种问题及解决方案,包括错误提示、原因分析和解决办法。涉及错误如类型错误、函数不支持、变量命名限制等,以及如何通过修改代码或使用trace规避问题。

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

目前网上使用torchscript导出实际模型的案例比较少,以下遇到的问题均是本人导出PatchmatchNet过程中遇到的问题

欢迎使用torchscript导出模型的同学们一起在评论区中讨论遇到的问题,尽量使得本文提出的问题能为我们以后避坑

  1. 出错提示:aten::div.Tensor(Tensor self, Tensor other) -> (Tensor):
    Expected a value of type ‘Tensor’ for argument ‘self’ but instead found type 'int
 torch.div(feature_channel, self.G, rounding_mode='trunc')
 整个改成
 int(feature_channel/self.G)
  1. 出错提示 RuntimeError: undefined value warped_feature
    355行注释掉 del warped_feature, src_feature, src_proj, similarity, view_weight

  2. 出错提示’int’ object has no attribute or method ‘div_’.:

similarity = similarity_sum.div_(pixel_wise_weight_sum)
改成
similarity = torch.div(similarity_sum, pixel_wise_weight_sum)
或(两个重建的效果不同)
similarity = torch.div(similarity_sum, pixel_wise_weight_sum, rounding_mode='trunc')
  1. Expected a value of type ‘Tensor’ for argument ‘x1’ but instead found type ‘float’
    原因:本来就是tensor的,但是script检测不出来,所以传入前显示的告诉它是tensor转换
score = self.similarity_net(similarity, grid, weight)  # [B, Nde
pth, H, W]
改成
score = self.similarity_net(torch.tensor(similarity), grid, weight)  # [B, Ndepth, H, W]
  1. torch.jit.frontend.FrontendError: Cannot instantiate class ‘LogSoftmax’ in a script function
    原因:可能真的不支持这个函数吧,但是看了TorchScript — PyTorch 1.13 documentation,里面torchscript对pytorch的支持功能函数是有这个的,最后改用
    import torch.nn.functional as F 用这里面的logsoftmax
    原本使用 import torch.nn 里面的logsoftmax的
softmax = nn.LogSoftmax(dim=1)
score = softmax(score)
改成
score = F.log_softmax(score, dim=1)
  1. Expected a default value of type Tensor on parameter “grid”.
    原因:可能不能再forward的默认参数列表里面用None
grid: torch.Tensor = None,
weight: torch.Tensor = None,
view_weights: torch.Tensor = 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rhys___

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值