在你的情况下它工作的原因retain_graph=True
是你有一个非常简单的图表,可能没有内部中间缓冲区,反过来没有缓冲区会被释放,所以不需要使用retain_graph=True
.
但是,当向您的图表添加额外的计算时,一切都在发生变化:
代码:
x = torch.ones(2, 2, requires_grad=True)
v = x.pow(3)
y = v + 2
y.backward(torch.ones(2, 2))
print('Backward 1st time w/o retain')
print('x.grad:', x.grad)
print('Backward 2nd time w/o retain')
try:
y.backward(torch.ones(2, 2))
except RuntimeError as err:
print(err)
print('x.grad:', x.grad)
输出:
Backward 1st time w/o retain
x.grad: tensor([[3., 3.],
[3., 3.]])
Backward 2nd time w/o retain
Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
x.grad: tensor([[3., 3.],
[3., 3.]]).
在这种情况下,额外的 internalv.grad
将被计算,但torch
不存储中间值(中间梯度等),并且 withretain_graph=False
v.grad
将在 first 之后被释放backward
。
因此,如果您想第二次反向传播,您需要指定retain_graph=True
“保留”图形。
代码:
x = torch.ones(2, 2, requires_grad=True)
v = x.pow(3)
y = v + 2
y.backward(torch.ones(2, 2), retain_graph=True)
print('Backward 1st time w/ retain')
print('x.grad:', x.grad)
print('Backward 2nd time w/ retain')
try:
y.backward(torch.ones(2, 2))
except RuntimeError as err:
print(err)
print('x.grad:', x.grad)
输出:
Backward 1st time w/ retain
x.grad: tensor([[3., 3.],
[3., 3.]])
Backward 2nd time w/ retain
x.grad: tensor([[6., 6.],
[6., 6.]])