您已经回答了自己的问题,即下划线表示 PyTorch 中的就地操作。但是我想简要指出为什么就地操作可能会出现问题:
这是从您发布的答案中截取的经过稍微修改的示例:
首先是就地版本:
import torch
a = torch.tensor([2, 4, 6], requires_grad=True, dtype=torch.float)
adding_tensor = torch.rand(3)
b = a.add_(adding_tensor)
c = torch.sum(b)
c.backward()
print(c.grad_fn)
导致此错误的原因:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-27-c38b252ffe5f> in <module>
2 a = torch.tensor([2, 4, 6], requires_grad=True, dtype=torch.float)
3 adding_tensor = torch.rand(3)
----> 4 b = a.add_(adding_tensor)
5 c = torch.sum(b)
6 c.backward()
RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.
其次是非就地版本:
import torch
a = torch.tensor([2, 4, 6], requires_grad=True, dtype=torch.float)
adding_tensor = torch.rand(3)
b = a.add(adding_tensor)
c = torch.sum(b)
c.backward()
print(c.grad_fn)
效果很好 - 输出:
<SumBackward0 object at 0x7f06b27a1da0>
因此,作为外卖,我只想指出在 PyTorch 中谨慎使用就地操作。