26

In PyTorch what is the difference between new_ones() vs ones(). For example,

x2.new_ones(3,2, dtype=torch.double)

vs

torch.ones(3,2, dtype=torch.double)
1
  • What is your variable x2 in this instance?
    – dennlinger
    Oct 18, 2018 at 8:38

2 Answers 2

27

For the sake of this answer, I am assuming that your x2 is a previously defined torch.Tensor. If we then head over to the PyTorch documentation, we can read the following on new_ones():

Returns a Tensor of size size filled with 1. By default, the returned Tensor has the same torch.dtype and torch.device as this tensor.

Whereas ones()

Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument sizes.

So, essentially, new_ones allows you to quickly create a new torch.Tensor on the same device and data type as a previously existing tensor (with ones), whereas ones() serves the purpose of creating a torch.Tensor from scratch (filled with ones).

2
  • What are the benefits of this? When would I use one instead of the other?
    – typhon04
    Jan 30, 2021 at 7:38
  • 2
    new_ones() can be used on an existing tensor, like x = torch.tensor(); x.new_ones([2,3]). This allows you to move your tensor x freely across devices or compute the dimensions, before actually initializing it. ones(), on the other hand, directly creates a new tensor: x = torch.ones([2,3]).
    – dennlinger
    Jan 30, 2021 at 12:17
6

new_ones()

# defining the tensor along with device to run on. (Assuming CUDA hardware is available)

x = torch.rand(5, 3, device="cuda")

new_ones() works with existing tensor. y will inherit the datatype from x and it will run on same device as defined in x

y = x.new_ones(2, 2)
print(y)

Output:

tensor([[1., 1.],
        [1., 1.]], device='cuda:0')

ones()

# defining tensor. By default it will run on CPU.
x = torch.ones(5, 3)
print(x)

Output:

tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])

ones() is used to define tensor with 1. (as shown in example) of given size and is not dependent on the existing tensor, whereas new_ones() works with existing tensor which inherits properties like datatype and device from existing tensor and define the tensor with given size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.