The code looks generally OK.
What happens, if you remove loss.requires_grad = True? You should generally only be able to change the requires_grad attribute of leaf variables. Does the loss tensor contain a valid grad_fn?