from https://blog.csdn.net/appleml/article/details/80143212
contiguous:view只能用在contiguous的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。
一种可能的解释是:
有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式。
判断是否contiguous用torch.Tensor.is_contiguous()函数。
import torch
x = torch.ones(10, 10)
print(x.is_contiguous()) # True
print(x.transpose(0, 1).is_contiguous()) # False
print(x.transpose(0, 1).contiguous().is_contiguous()) # True
print(x.view(2, 50).shape) # torch.Size([2, 50])
# 报错
# RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
# print(x.transpose(0, 1).view(2, 50).shape)
# 替换方法
print(x.transpose(0, 1).reshape(2, 50).shape) # torch.Size([2, 50])
print(x.transpose(0, 1).contiguous().view(2, 50).shape) # torch.Size([2, 50])
在pytorch的最新版本0.4版本中,增加了torch.reshape(), 这与 numpy.reshape 的功能类似。它大致相当于 tensor.contiguous().view()