Bootstrap

pytorch导出torchscript记录

目前网上使用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 = 
;