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

用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

 1 import torch._utils
 2 try:
 3     torch._utils._rebuild_tensor_v2
 4 except AttributeError:
 5     def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
 6         tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)
 7         tensor.requires_grad = requires_grad
 8         tensor._backward_hooks = backward_hooks
 9         return tensor
10     torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2

猜你喜欢

转载自www.cnblogs.com/yourcool/p/9477972.html