contigous 在英文中为

连续的意思,何为连续,就是语义相同的张量存储在连续的内存空间中,

为什么要使用contigous?

因为view()操作需要连续的tensor

transpose、permute 操作虽然没有修改底层一维数组,但是新建了一份Tensor元信息,并在新的元信息中的 重新指定 stride。torch.view 方法约定了不修改数组本身,只是使用新的形状查看数据。如果我们在 transpose、permute 操作后执行 view,Pytorch 会抛出以下错误。


x = torch.arange(12).reshape(4,3)
print(x)
print(x.stride())##步长
'''
tensor([[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]])
(3, 1)
'''
x1 = x.transpose(0,1)
print(x1)
print(x1.stride())
'''
tensor([[ 0,  3,  6,  9],
        [ 1,  4,  7, 10],
        [ 2,  5,  8, 11]])
(1, 3)

'''

print(x.data_ptr()== x1.data_ptr())

print(x.is_contiguous(), x1.is_contiguous())
''':cvar
True
True False

'''
# x2 = Tensor.flatten(x)
# print(x2)
#
# x3 = Tensor.flatten(x1)
# print(x3)
x3= x.view(-1)##拉平,观察底层数据
print(x3)
# x4 = x1.view(-1)
# print(x4)##会报错,因为步长的改变。view 仅在底层数组上使用指定的形状进行变形
''':cvar
  File "C:/Users/adcar/PycharmProjects/pythonProject2/NLP/transformer/yufa1.py", line 222, in <module>
    x4 = x1.view(-1)
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.

'''
x5 = x1.contiguous().view(-1)##而通过contiguous让其变得连续后就可以使用view
print(x5)
''':cvar
tensor([ 0,  3,  6,  9,  1,  4,  7, 10,  2,  5,  8, 11])
'''
print(x5.data_ptr()== x3.data_ptr())##但是contiguous()创建了一块新的内存,所以他们的地址是不是同的
'''

False

'''

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐