Contiguous란?

Example

import torch

a = torch.randn(3, 4)
a.transpose_(0, 1)
b = torch.randn(4, 3)

print(a)
print(b)

"""
tensor([[-0.1741,  0.1139, -0.4796],
        [-1.3149, -1.7699, -0.1786],
        [ 1.9126,  0.8987,  0.0856],
        [-0.5147, -0.4866,  0.2893]])
tensor([[-0.9518,  0.4973,  0.5413],
        [ 0.3912, -0.2460,  0.1408],
        [-0.4150,  0.6952,  2.5735],
        [-0.4103, -0.0185,  0.0356]])
"""
for i in range(4):
    for j in range(3):
        print(a[i][j].data_ptr())
"""
94882007243648
94882007243664
94882007243680
94882007243652
94882007243668
94882007243684
94882007243656
94882007243672
94882007243688
94882007243660
94882007243676
94882007243692
"""

for i in range(4):
    for j in range(3):
        print(b[i][j].data_ptr())
"""
94882007353280
94882007353284
94882007353288
94882007353292
94882007353296
94882007353300
94882007353304
94882007353308
94882007353312
94882007353316
94882007353320
94882007353324
"""

Untitled

a같이 자료 저장 순서가 원래 방향과 어긋난 경우를 contiguous = False 상태라고 한다.

각 텐서에 stride() 메소드를 호출하여 데이터의 저장 방향을 조회할 수 있다.

또한, is_contiguous() 메소드로 contiguous=True 여부도 쉽게 파악할 수 있다.

a.stride() # (1, 4)
b.stride() # (3, 1)

a.is_contiguous() # False
b.is_contiguous() # True

여기에서, a.stride() 결과가 (1, 4)라는 것은

a[0][0] → a[1][0]으로 증가할 때는 자료 1개 만큼의 메모리 주소가 이동되고,