I have a simple input tensor x and a function f(x) = 2*x. The gradient of x is df/dx = 2. How to get this result using pytorch? This is what I tried:
x = torch.tensor([0.0, 1.0], requires_grad = True)
f = 2*x
f.backward()
print(x.grad)

This throws the following error:
RuntimeError: grad can be implicitly created only for scalar outputs
Then I tried:
x = torch.tensor([0.0, 1.0], requires_grad = True)
f = 2*x
f.backward(torch.FloatTensor([1, 1]))
print(x.grad)

This works, returning the following result: tensor([2., 2.]). I am still not sure though why f.backward() doesn’t work and what is the explanation of torch.FloatTensor([1, 1]). Ideally I would expect to get 2. and not [2., 2.].
However, the following returns None:
x = torch.tensor([0.0, 1.0], requires_grad = True)
y = 1*x
f = 2*y
f.backward(torch.FloatTensor([1, 1]))
print(y.grad)

Why is this happening?