Hi,
In general, you should never use .data otherwise you might get unexpected behaviors like that.
The other error comes from the fact that you modify a leaf Tensor inplace. You can add a opt_weights = opt_weights.clone() before this code to make sure you don’t modify the original Tensor.