AttributeError: 'MemoryBank' object has no attribute '_backward_hooks'
时间: 2023-10-04 10:12:46 浏览: 250
当出现"AttributeError: 'MemoryBank' object has no attribute '_backward_hooks'"这个错误时,它通常表示在MemoryBank对象中找不到_backward_hooks属性。这个错误通常是由于使用了过时的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_grad
tensor._backward_hooks = backward_hooks
return tensor
torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2
```
这段代码会为旧版本的pytorch添加一个_rebuild_tensor_v2函数,以解决_backward_hooks属性缺失的问题。
另外,当自定义的loss函数在调用loss.backward()时报错,并且经过检查感觉没有问题时,可能是在初始化的时候忘记添加self关键字。请确保在自定义loss函数的初始化方法中正确地添加了self关键字。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [AttributeError: 'module' object has no attribute '_rebuild_tensor_v2' 解决方法](https://blog.csdn.net/qq_37828488/article/details/100023884)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [AttributeError: ‘Myloss‘ object has no attribute ‘_backward_hooks](https://blog.csdn.net/weixin_43405472/article/details/124523477)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文