错误:
RuntimeError: 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.
详细信息:
Traceback (most recent call last):
File "main.py", line 21, in <module>
startTrain.run(trainBatch)
File "/root/train.py", line 49, in run
loss.backward()
File "/usr/local/lib/python3.7/site-packages/torch/tensor.py", line 102, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/usr/local/lib/python3.7/site-packages/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: 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.
原因:
程序在试图执行backward的时候,发现计算图的缓冲区已经被释放。
解决办法:
在
backward()
函数中添加参数
retain_graph=True
:
即:
改为: