天天看點

RuntimeError: Trying to backward through the graph a second time, but the buffers have already been

錯誤:

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

即:

改為:

繼續閱讀