The issue is that you are modifying a leaf tensor in-place when you do a = torch.tensor(1., requires_grad=True); a[1] = foo
The error you are getting is a bit cryptic indeed. If you actually run the code again in version 1.8 and above, performing a in-place op now performs the check during forward and will give you: RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.