Search code examples
pytorchreshapetensortorch

Is reshape() same as contiguous().view()?


In PyTorch, for a tensor x is x.reshape(shape) always equivalent to x.contiguous().view(shape)?


Solution

  • No. There are some circumstances where .reshape(shape) can create a view, but .contiguous().view(shape) will create a copy.

    Here is an example:

    x = torch.zeros(8, 10)
    y = x[:, ::2]
    z0 = y.reshape(40)               # Makes a new view
    z1 = y.contiguous().view(40)     # Makes a copy
    

    We can confirm that z0 is a new view of x, but z1 is a copy:

    > x.data_ptr() == z0.data_ptr()
    True
    > x.data_ptr() == z1.data_ptr()
    False