How to create a PyTorch mutable tensor?
I'm trying to create a copy of a tensor that will change if the original changes.
r = torch.tensor(1.0, requires_grad=True)
p = r.clone()
print('before')
print(r)
print(p)
r = r*5
print('after')
print(r)
print(p)

&gt;&gt;&gt;
before
tensor(1., requires_grad=True)
tensor(1.)
after
tensor(5., grad_fn=&lt;MulBackward0&gt;)
tensor(1.)

I tried with clone(), detach(), and even simply p=r, nothing worked.
Update.
Tried view:
r = torch.tensor(1.0, requires_grad=True)
p = r.view(1)
print('before')
print(r)
print(p)
r = r*5
print('after')
print(r)
print(p)

&gt;&gt;&gt;before
tensor(1., requires_grad=True)
tensor([1.], grad_fn=&lt;ViewBackward&gt;)
after
tensor(5., grad_fn=&lt;MulBackward0&gt;)
tensor([1.], grad_fn=&lt;ViewBackward&gt;)


What your looking for a is a view(which is a shallow copy of the tensor), numpy also follows this as well, the below contains what you want
test = torch.tensor([100])
test_copy = test.view(1)

print(test, test_copy) # tensor([100]) tensor([100])
test[0] = 200
test, test_copy # (tensor([200]), tensor([200]))

Edit: Made some changes and found out the problem
r = torch.tensor(1.0, requires_grad=True) # Remove requires_grad if you really dont need it
p = r.view(1)
print('before')
print(r)
print(p)
with torch.no_grad(): # Had to use this if not wont be able to do math ops cause gradients are being tracked
  # Problem here was that you redeclared a new variable of r so you wiped out the previous reference to the tensor
  r.mul_(5) # Simple calculations
print('after')
print(r)
print(p)

