[英]How to break PyTorch autograd with in-place ops
我試圖更好地理解就地操作在 PyTorch autograd 中的作用。 我的理解是它們可能會導致問題,因為它們可能會覆蓋后退步驟所需的值。
我正在嘗試構建一個示例,其中就地操作破壞了自動微分,我的想法是在使用它來計算其他張量后覆蓋反向傳播期間所需的一些值。
我使用分配作為就地操作(我嘗試了+=
並得到了相同的結果),我以這種方式仔細檢查了它是一個就地操作:
x = torch.arange(5, dtype=torch.float, requires_grad=True)
y = x
y[3] = -1
print(x)
印刷:
tensor([ 0., 1., 2., -1., 4.], grad_fn=<CopySlices>)
這是我打破 autograd 的嘗試:
x = torch.arange(5, dtype=torch.float, requires_grad=True)
out1 = x ** 2
out2 = out1 / 10
# out1[3] += 100
out2.sum().backward()
print(x.grad)
這打印
tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000])
x = torch.arange(5, dtype=torch.float, requires_grad=True)
out1 = x ** 2
out2 = out1 / 10
out1[3] = 0
out2.sum().backward()
print(x.grad)
這打印:
tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000])
我期待獲得不同的畢業生。
grad_fn=<CopySlices>
。破壞 autograd 的就地操作的工作示例:
x = torch.ones(5, requires_grad=True)
x2 = (x + 1).sqrt()
z = (x2 - 10)
x2[0] = -1
z.sum().backward()
提高:
RuntimeError: one of the variables needed for gradient computation has been modified by an in-place operation: [torch.FloatTensor [5]], which is output 0 of SqrtBackward, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.