pytorch中的contiguous

pytorch中的contiguous,第1张

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 
    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

'''

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/728011.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存