pytorch版本问题:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'

2023-03-05,,

pytorch加载训练好的模型的时候遇到了如下的问题:

AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'

到网上查了一下是由于训练模型时使用的是新版本的pytorch,而加载时使用的是旧版本的pytorch。

解决方法:

1、既然是pytorch版本较老,那最简单的解决方法当然是简单的升级一下pytorch就ok了。

2、国外的大神给了另一种解决方法,就是在程序开头添加下面的代码,即可以使老版本pytorch兼容新版本pytorch,参考链接https://discuss.pytorch.org/t/question-about-rebuild-tensor-v2/14560

 import torch._utils
try:
torch._utils._rebuild_tensor_v2
except AttributeError:
def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)
tensor.requires_grad = requires_grad
tensor._backward_hooks = backward_hooks
return tensor
torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2

pytorch版本问题:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'的相关教程结束。

《pytorch版本问题:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'.doc》

下载本文的Word格式文档,以方便收藏与打印。