NLP Tutorial (1) - Pytorch 기초

이로운·2025년 6월 5일

NLP_tutorial

목록 보기
1/8

금일부터 자연어 처리와 관련된 기술 튜토리얼을 시작하고자 합니다.

참고로 본인은 Robotics Engineer로, SLAM(Simultaneous Localization and Mapping)과 Perception 관련 기술을 주로 전공하였고, 머신러닝이나 AI 관련 지식은 매우 빈약한 편으로, 혹여나 저와 비슷한 지식 레벨의 독자분들께 도움이 되셨으면 좋겠습니다.

주로 참고하는 서적은 '파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층 학습'을 활용할 계획입니다.

이번 챕터는 Pytorch 기초 및 관련 개념을 공부해보려 합니다.

(1) 파이토치 기초

텐서(Tensor)와 텐서의 생성

우선 텐서(Tensor)의 개념을 알아야합니다. 사실, 텐서는 이미 다른 곳에서도 많이 다루고 있는 개념입니다. 우리는 python의 numpy나 C++에서의 Eigen을 활용하여 수 없이 벡터와 행렬을 다뤄 많은 문제를 풀고 있으며, 벡터와 행렬은 모두 텐서의 한 형태입니다. 정리하자면

0차원 텐서 : 스칼라
1차원 텐서 : 벡터
2차원 텐서 : 행렬
3차원 텐서 : 3차원 배열
4차원 ...

이렇게 말할 수 있을 것 같습니다. 이 중, 행렬은 회색조(Grayscale) 사진을 표현할 때, 3차원 배열은 컬러 정보가 있는 사진을 나타낼 때 사용합니다. 그렇다면, 4차원 텐서는 3차원 배열의 묶음으로 여러 이미지들의 묶음이라고 생각할 수 있겠죠.

이제 본격적으로 코드에서 텐서를 생성하고 출력해봅시다.

import torch

print(torch.tensor([1, 2, 3.0]))
print(torch.Tensor([[1, 2, 3], [4, 5, 6]]))
print(torch.tensor([]))
print(torch.Tensor([]))
print(torch.LongTensor([1.1, 2.2, 3.3]))
print(torch.FloatTensor([1, 2, 3]))

출력 결과

tensor([1., 2., 3.])
tensor([[1., 2., 3.],
        [4., 5., 6.]])
tensor([])
tensor([])
tensor.py:7: DeprecationWarning: an integer is required (got type float).  Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
  print(torch.LongTensor([1.1, 2.2, 3.3]))
tensor([1, 2, 3])
tensor([1., 2., 3.])

위 코드를 보면 tensor와 Tensor가 혼재 되어 사용되어 있는걸 확인할 수 있습니다. 소문자 tensor는 입력된 데이터를 복사해 텐서로 변환하는 함수로, 입력된 데이터 형식에 적합한 텐서 자료형으로 자동으로 변환합니다.

Tensor는 기본형으로, 자료형이 명확히 표현되는 클래스 형태이다. LongTensor와 FloatTensor는 torch.Tensor 클래스를 상속받은 데이터 형식으로, int, boolean, double 등의 형식이 있다.

텐서 차원 변환

import torch

tensor = torch.rand(1,2)
tensor_reshape = tensor.reshape(2,1)
print(tensor)
print(tensor_reshape)
tensor([[0.3729, 0.2039]])
tensor([[0.3729],
        [0.2039]])

텐서의 차원 변환은 위와 같이 이뤄지며, Eigen이나 Numpy를 많이 다뤄 본 사람이라면 익숙할 것이다. 차원 변환은 연산 과정이나 입출력 변환 등에서 많이 사용된다.

텐서 자료형 및 장치 설정

텐서 자료형은 기본으로 설정될 Tensor의 타입을 지정하며, 장치 설정은 GPU 학습에서 가장 중요한 설정으로 장치를 정확히 할당하지 않으면 Runtime Error가 발생할 위험이 있다. 따라서, 모델 학습 전에 장치 설정을 늘 확인하도록 한다. 자료형 및 장치 설정은 아래와 같이 확인 가능하다.

# 자료형 설정
import torch

tensor = torch.rand((3, 3), dtype=torch.float)
print(tensor)

tensor2 = torch.randint(low=0, high=10, size=(3, 3), dtype=torch.int)
print(tensor2)
tensor([[0.7739, 0.4538, 0.2664],
        [0.6215, 0.3935, 0.7953],
        [0.3121, 0.8309, 0.6427]])
tensor([[9, 1, 4],
        [8, 8, 0],
        [8, 5, 8]], dtype=torch.int32)
# 장치 확인 및 설정
import torch

device = "cuda" if torch.cuda.is_available() else "cpu"
cpu = torch.FloatTensor([1, 2, 3])
gpu = torch.cuda.FloatTensor([1, 2, 3])
tensor = torch.rand((1, 1), device=device)
print(device)
print(cpu)
print(gpu)
print(tensor)

# 변환
cpu = torch.FloatTensor([1, 2, 3])
gpu = cpu.cuda()
gpu2cpu = gpu.cpu()
cpu2gpu = cpu.to("cuda")
print(cpu)
print(gpu)
print(gpu2cpu)
print(cpu2gpu)
tensor.py:6: UserWarning: The torch.cuda.*DtypeTensor constructors are no longer recommended. It's best to use methods such as torch.tensor(data, dtype=*, device='cuda') to create tensors. (Triggered internally at ../torch/csrc/tensor/python_tensor.cpp:78.)
  gpu = torch.cuda.FloatTensor([1, 2, 3])
cuda
tensor([1., 2., 3.])
tensor([1., 2., 3.], device='cuda:0')
tensor([[0.7823]], device='cuda:0')
tensor([1., 2., 3.])
tensor([1., 2., 3.], device='cuda:0')
tensor([1., 2., 3.])
tensor([1., 2., 3.], device='cuda:0')

장치 확인 및 설정 부분을 살펴보면, 장치 설정은 device 매개 변수의 장치 속성을 할당해 설정할 수 있다. Tensor 클래스의 경우, CUDA용 클래스가 별도로 존재하므로, 해당 클래스를 사용하면 되며, 장치간 상호 변환은 cuda와 cpu 메서드를 통해 할 수 있다.

추가로 확인해볼건, 위의 경고 메시지이다. 사실 CUDA용 텐서 생성자는 더이상 권장되지는 않는 방식이다(꽤 예전부터). 따라서 권장되는 방식은

x_cpu = torch.tensor([1, 2, 3], device='cpu')    # CPU 텐서
x_gpu = torch.tensor([1, 2, 3], device='cuda')   # GPU(CUDA) 텐서

이렇게 명시하는 것을 권장한다.

profile
Robotics Engineer / https://www.linkedin.com/in/roun-lee-5503382b6/

0개의 댓글