Unable to solve the "Trying to backward through the graph a second time" Error in PyTorch
I am trying to do a simple weight update using the optimizer like below:
x = torch.rand(10, requires_grad=True)
y = x * 15. + 10.

optimizer = torch.optim.Adam
loss = torch.nn.MSELoss()

def train(x, y, loss, ep, opti):
  
  w = torch.rand(1, dtype=torch.float32, requires_grad=True)
  b = torch.rand(1, dtype=torch.float32, requires_grad=True)

  op = opti([w, b])

  for e in range(ep):
    
    y_hat = x.multiply(w) + b
    l = loss(y_hat, y)
    
    print(f'Epoch: {e}, loss: {l}')
    l.backward()
    
    op.step()
    op.zero_grad()

  return w, b

w_hat, b_hat = train(x, y, loss, 10, optimizer)

However I am getting the Trying to backward through the graph a second time error even though I am not aware why as I am zeroing the gradients at each step.
Do you have any suggetions?

The reason is x
Please change first line to x = torch.rand(10)
