I don’t see anything obviously wrong in your code.
Could you print the output and labels tensors before calling loss.backward()?
Maybe we could isolate this issue to these values and reproduce the error.
If these tensors do not yield the same error, could you additionally also store the state_dict of your model and the current imgs?