saandeep_aathreya:

loss1.backward(retain_graph=True)
optimizer.step()
loss2.backward(retain_graph=False)  //ERROR HERE
optimizer2.step()



You are making one simple mistake. You are calling the second loss2.backward() after the first optimizer.step()
# NO ERROR
loss1.backward(retain_graph=True)
loss2.backward(retain_graph=False)
optimizer.step()
optimizer2.step()

The reason is that once you call optimizer.step() the variables are updated with the grads. When you again call loss2.backward() the grads have already been used to update the variables since in your case the variables(parameters) are common
Hope this helps