Your posted code could work assuming your model is small and you have enough memory.
Assuming you are summing the losses inside the DataLoader loop, this approach would store the computation graphs, which would allocate more memory in each iteration.
Depending on the size of your dataset, you might be quickly running out of memory.
As an alternative, you could call backward() on each loss in each iteration, so that Autograd can free the intermediate tensors, as they are not needed anymore.