当前位置: 代码迷 >> 综合 >> AttributeError: 'module' object has no attribute '_rebuild_tensor_v2' 解决方法
  详细解决方案

AttributeError: 'module' object has no attribute '_rebuild_tensor_v2' 解决方法

热度:79   发布时间:2023-11-26 12:22:36.0

问题描述

用pytorch加载训练好的模型时,可能会遇到下面的问题:

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

原因

由于训练模型时使用的是新版本的pytorch,而加载时使用的是旧版本的pytorch。

解决方法

1、升级pytorch到适当的新版本

2、或者,在程序开头添加下面的代码,以使老版本pytorch兼容新版本pytorch:

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_gradtensor._backward_hooks = backward_hooksreturn tensortorch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2

 

  相关解决方案