# Runtime Error in .backward()

**URL:** <https://discuss.pytorch.org/t/runtime-error-in-backward/67241>\
**Category:** autograd\
**Created:** [January 21, 2020, 8:24am UTC](https://discuss.pytorch.org/t/runtime-error-in-backward/67241 "2020-01-21T08:24:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![fsattler](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/f/4da419/32.png) [@fsattler](https://discuss.pytorch.org/u/fsattler)\
**Post date:** [January 21, 2020, 8:24am UTC](https://discuss.pytorch.org/t/runtime-error-in-backward/67241/1 "2020-01-21T08:24:05Z")

</div>

Hi! The following code:

```auto
import torch
h_ = torch.nn.Parameter(torch.ones([1,1]))
h = h_**2
optimizer = torch.optim.SGD([h_], lr=0.1)

for _ in range(2):
  optimizer.zero_grad()
  loss = h.sum()
  loss.backward()
  optimizer.step()

```

throws a

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.

Can anyone tell me whats the issue? Thanks!

---

<div class="post-metadata">

**Author:** ![anantguptadbl](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/anantguptadbl/32/17784_2.png) [@anantguptadbl](https://discuss.pytorch.org/u/anantguptadbl)\
**Post date:** [January 21, 2020, 1:38pm UTC](https://discuss.pytorch.org/t/runtime-error-in-backward/67241/2 "2020-01-21T13:38:16Z")

</div>

Try this code

```auto
import torch

h_ = nn.Parameter(torch.ones([1,1]),requires_grad=True)
optimizer = torch.optim.SGD([h_], lr=0.01)

for _ in range(10):
    optimizer.zero_grad()
    hOut=h_**2 - h_*10
    loss = hOut.sum()
    loss.backward()
    optimizer.step()
    print(loss.item())

```

What I have done is inserted the calculation of hOut within the loop itself. Let us take a look at the changes in the graphical manner

 ![image](https://discuss.pytorch.org/uploads/default/original/3X/f/0/f09442a8df4711185cb81be5931d0b1b6c758eac.png)

Since you were not recalculating H within each loop, it freed the buffer after the first LOSS Bakcward. The next loop it threw and error  
We included the the recalculation of H within the loop so that the buffer is refilled. Hope this helps.

---

<div class="post-metadata">

**Author:** ![fsattler](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/f/4da419/32.png) [@fsattler](https://discuss.pytorch.org/u/fsattler)\
**Post date:** [January 21, 2020, 2:02pm UTC](https://discuss.pytorch.org/t/runtime-error-in-backward/67241/3 "2020-01-21T14:02:12Z")

</div>

I see. That fixes the problem. Thanks alot! 🙂
