Since you are setting prev_loss=loss, you will backpropagate through the computation graph multiple times, so you would need to set retain_graph=True in the backward call.
Assigning prev_loss = loss in the no_grad block will not detach prev_loss from the computation graph, as just new operations won’t require gradients.