Thanks ptrblack, but when I add the lines you proposed, I get another error message during the calculation of the loss and backwarding it:

RuntimeError: cuda runtime error (710) : device-side assert triggered at C:/cb/pytorch_1000000000000/work/aten/src\THC/generic/THCTensorMath.cu:29

After that, if I try to run the code again, I alawys get the following error message:

RuntimeError: CUDA error: device-side assert triggered

This one is raised with passing the model to cuda, quiet in the beginning of the code.
EDIT:
I solved this error by substracting 1 to each label:
labels = labels - 1
The indexing of the labels should start with 0 and end with the number of classes - 1. Is this correct?