在写代码过程中遇到了RuntimeError: Trying to backward through the graph a second time 问题。我在网络上没有找到合适的解决方案,并且我的原始工程代码比较复杂,难以直接询问chatgpt。为了更方便debug,我写了一个简单的代码复现这个错误。
import torch
import torch.nn as nn
import torch.optim as optim
class A(nn.Module):
def __init__(self):
super(A, self).__init__()
self.fc = nn.Linear(512, 512)
self.v_image = nn.Parameter(torch.randn(1, 512))
self.fuse_image = []
def forward(self, x):
out = self.fc(x)
t = torch.matmul(out, self.v_image.T)
self.fuse_image.append(t)
return out, self.fuse_image
model = A()
criterion = nn.L1Loss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
for i in range(50):
optimizer.zero_grad()
x = torch.randn(2, 512)
out, fuse_image = model(x)
y = torch.mean(fuse_image[0])
loss = criterion(y, torch.tensor(1.1))
loss.backward()
print(loss)
optimizer.step()
运行这段代码,出现报错RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward。
问题出现在self.fuse_image = [],将fuse_image定义在forward函数中即可解决问题。更改后的代码如下:
import torch
import torch.nn as nn
import torch.optim as optim
class A(nn.Module):
def __init__(self):
super(A, self).__init__()
self.fc = nn.Linear(512, 512)
self.v_image = nn.Parameter(torch.randn(1, 512))
def forward(self, x):
fuse_image = []
out = self.fc(x)
t = torch.matmul(out, self.v_image.T)
fuse_image.append(t)
return out, fuse_image
model = A()
criterion = nn.L1Loss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
for i in range(50):
optimizer.zero_grad()
x = torch.randn(2, 512)
out, fuse_image = model(x)
y = torch.mean(fuse_image[0])
loss = criterion(y, torch.tensor(1.1))
loss.backward()
print(loss)
optimizer.step()
chatgpt对这个问题的解释如下:
每次调用 .backward()
后,PyTorch 会释放计算图的中间变量,以节省内存。你在 fuse_image.append(t)
中将一个中间变量 t
存储到 fuse_image
中,这个中间变量 t
其实是计算图的一部分,在进行第一次反向传播时(即调用 loss.backward()
),该计算图的中间变量会被清空。
即便你在第二次前向传播时重新构建了计算图,fuse_image
中存储的是第一次前向传播时的计算图的一部分,而它已经在第一次 .backward()
调用时被释放了。这就是为什么在你访问 fuse_image[0]
时会遇到错误的原因。
fuse_image
中的张量 t
。.backward()
,此时计算图会被释放,以节省内存。fuse_image[0]
中存储的是上一次前向传播时的中间结果,而计算图已经被释放,导致访问它时报错。因篇幅问题不能全部显示,请点此查看更多更全内容