If you are using with torch.no_grad():, you explicitly say you don’t want to calculate gradients for the operations inside this block, so loss.backward() won’t work. Usually you use it for the validation/test dataset.
If you need to call loss.backward() you shouldn’t use it.