pytorch中的contiguous

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

'''

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值