user14675723
user14675723

Reputation:

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

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

Upvotes: 2

Views: 1503

Answers (1)

myrtlecat
myrtlecat

Reputation: 2276

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

Upvotes: 3

Related Questions