How to transfer a grad attribute from tensor to tensor?


I would like to know if it is possible to transfer the .grad attribute of a tensor, e.g, y to a z tensor which does not have one.

To simplify my problem:

import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = tensor([[3, 3], [3, 3]])

I would like then to transfer y.grad_fn to z. More specifically I want to, in a way, save grad_fn of a tensor and give it later to a new tensor.

Thank you in advance.
Best regards,

You can set the .grad attribute to a specific value, but I don’t think you can add a .grad_fn to a tensor directly.