.contiguous

2023. 7. 12. 20:05

Pytorch 를 사용하며 Tensor 의 차원을 바꾸거나 변화시키는 등의 조작을 할 떄, 가끔씩 다음과 같은 에러가 발생할 때가 있습니다.

 

RuntimeError: input is not contiguous

 

contiguous 를 Pytorch 공식 문서에서 살펴보면 다음과 같은 설명이 나옵니다.

 

Returns a contiguous in memory tensor containing the same data as self tensor. If self tensor is already in the specified memory format, this function returns the self tensor.

 

contiguous 란 어떤 의미일까? contiguous 의 의미는 인접한, 근접한 이라고 한다.

 

즉 Contiguous 상태를 가지고 있는 Tensor 는, 요소들이 선형적이고 연속적인 방식으로 메모리에 저장되는 Tensor를 얘기합니다. 텐서 내의 요소들의 메모리 주소가 간격이나 불연속성 없이 순차적으로 증가한다는 것을 의미합니다.

 

reshape, index 및 slicing과 같은 작업을 하려면 Contiguous tensor 형태로 메모리에 연속적으로 저장되어야 하기 때문에 중요하다고 할 수 있습니다. Tensor가 연속적으로 저장되지 않으면 이러한 연산은 예상치 못한 결과를 초래하거나 오류를 발생시킬 수 있습니다.

 

예를 들어 다음과 같은 코드를 예시로 들면

import torch

# Define a non-contiguous tensor
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]], stride=[3, 1])

try:
    reshaped_tensor = tensor.reshape(6, 1)
except Exception as e:
    print(e)

아래와 같은 에러가 발생할 수 있습니다

 

Reshaping a tensor which is not contiguous is not supported.

 

이를 해결하기 위해 Tensor의 .continuous() 를 호출하시면 됩니다. 이걸 호출하면 메모리에 지속적으로 저장이 보장되는 새로운 텐서를 반환하게 됩니다.

 

reshaped_tensor = tensor.contiguous().reshape(6, 1)