1. 程式人生 > >問題解決:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'

問題解決:AttributeError: 'module' object has no attribute '_rebuild_tensor_v2'

 於訓練模型時使用的是新版本的pytorch,而載入時使用的是舊版本的pytorch。

解決辦法:

  • 升級pytorch

看起來理所當然,其實有可能有坑。說不定還要轉回來。

  • 橋接

 在程式開頭新增下面的程式碼,即可以使老版本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