Does FloatTensor have attribute "requires_grad"?

I just tried the requires_grad in torch.tensor:

x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)

But when I used requires_grad in FloatTensor, I got an error:

xx = torch.FloatTensor([[1., -1.], [1., 1.]], requires_grad=True)
Traceback (most recent call last):
  File "/home/SSS/Desktop/SS/playground.py", line 54, in <module>
    xx = torch.FloatTensor([[1., -1.], [1., 1.]], requires_grad=True)
TypeError: new() received an invalid combination of arguments - got (list, requires_grad=bool), but expected one of:
 * (torch.device device)
 * (torch.Storage storage)
 * (Tensor other)
 * (tuple of ints size, torch.device device)
      didn't match because some of the keywords were incorrect: requires_grad
 * (object data, torch.device device)
      didn't match because some of the keywords were incorrect: requires_grad

Does FloatTensor have attribute “requires_grad”? If I want to set the flag for FloatTensor, how should I do?

1 Like

In your current example you’ll already create a torch.FloatTensor, since the type will be inferred automatically using the passed values.
However, if you would like to specify it, you could pass the dtype argument:

x = torch.tensor([[1., -1.], [1., 1.]], dtype=torch.float, requires_grad=True)
print(x.type())
> torch.FloatTensor
3 Likes