中文文档:
contiguous() → Tensor
返回一个内存连续的有相同数据的 tensor,如果原 tensor 内存连续则返回原 tensor
英文文档:
contiguous() → Tensor
Returns a contiguous tensor containing the same data as self tensor. If self tensor is contiguous, this function returns the self tensor.
常见用法:
contiguous 一般用于 transpose/permute 后和 view 前,即使用 transpose 或 permute 进行维度变换后,调用 contiguous,然后方可使用 view 对维度进行变形(如:tensor_var.contiguous().view() ),示例如下:
x = torch.Tensor(2,3)
y = x.permute(1,0) # permute:二维tensor的维度变换,此处功能相当于转置transpose
y.view(-1) # 报错,view使用前需调用contiguous()函数
y = x.permute(1,0).contiguous()
y.view(-1) # OK
两个可能原因
- view 函数只能用于 contiguous 后的 tensor 上,也就是只能用于内存中连续存储的 tensor。如果对 tensor 调用过 transpose, permute 等操作的话会使该 tensor 在内存中变得不再连续,此时就不能再调用 view 函数。因此,需要先使用 contiguous 来返回一个 contiguous copy。
- 维度变换后的变量是之前变量的浅拷贝,指向同一区域,即 view 操作会连带原来的变量一同变形,这是不合法的,所以也会报错。(这个解释有部分道理,也即 contiguous 返回了 tensor 的深拷贝 contiguous copy 数据)