Hi,
Few things:

Undefined Tensors are used in cpp to efficiently represent gradients full of 0s. So it is possible that you get an undefined Tensor here and for your optimization to be valid.
Just like in python, by default, the .grad() attribute is only saved for leaf Tensors. Otherwise, you will get an undefined Tensor. Is this Tensor a leaf? If not, you need to use .retain_grad() on it before calling .backward() to have its grad attribute populated.