That code looks fine yes.
Note that the retain_graph=True is not needed here.
Given the error in your original code, what might be happening as well is that you’re doing an optimizer step between the forward and the backward. And that optimizer step modifies the weights inplace which could lead to that error message.