Can't init a tensor with `randint` while `requires_grad=True`

Recently, I found that I can not initialize a random int tensor with randint while requires_grad is set to True.

To Reproduce

torch.randint(1, (10, 10), requires_grad=True)

RuntimeError: Only Tensors of floating point and complex dtype can require gradients

Additional information

  • Windows 10
  • torch version 1.9.0
  • python version 3.9.6

I don’t think this is my mistake in the usage way.
If this is a real bug, can I raise an issue in github torch repository? Thanks.

This is not a bug and expected behavior. As the error message explains, only floating point types (and complex types, which are also using floating point types internally) can require gradients.

1 Like