Based on the code snippet it seems that loss1 and loss2 would be constants, since you are detaching the output tensors, and thus be used in the gradient calculation (and will also raise the error using the second approach).
I’m not familiar with your use case, so could you explain, why the detaching is used?