pytorch报错:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'

转载自:

https://blog.csdn.net/qq_24305433/article/details/80844548

由于训练模型时使用的是新版本的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