본문 바로가기
C.W.K.
Stream
Lesson 03 of 11 · published

모양, 자료형, 장치: 세 숫자

~12 min · dtype, device, shape, metadata

Level 0텐서 탐구자
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

모든 텐서에는 기본 속성이 세 가지 있어

print(t)를 실행하면 PyTorch는 텐서의 값을 보여줘. 하지만 뭔가 깨졌을 때는 값보다 메타데이터가 훨씬 중요해. 다음 세 속성을 이 순서로 확인해:

  1. 모양: 각 차원의 크기야. 어떤 오류든 가장 먼저 확인해.
  2. 자료형: 원소를 표현하는 형식이야. 특히 혼합 정밀도 학습에서는 두 번째로 확인해야 해.
  3. 장치: 데이터가 물리적으로 놓인 곳이야. 'expected cuda:0 got cpu' 오류가 이 속성을 가리켜.

혼합 정밀도 학습이 본격적인 작업의 기본값이 된 만큼 자료형 계열은 익혀 두자.

  • torch.float32 (별칭 torch.float): 활성화와 가중치에 널리 쓰는 기본 자료형이야.
  • torch.float16 (별칭 torch.half): 메모리와 대역폭을 절반만 쓰지만 동적 범위가 좁아서 GradScaler가 필요해.
  • torch.bfloat16: float32와 지수 범위는 같고 가수 정밀도는 낮아. Ampere 이상 GPU와 Apple Silicon에서 쓰는 현대적인 혼합 정밀도 자료형이며, 보통 GradScaler가 필요 없어.
  • torch.float64 (double): 배정밀도 자료형이야. 과학 계산이나 수치 문제를 의심할 때 쓰며 학습의 기본값은 아니야.
  • torch.int64 (long): 클래스 레이블과 인덱스, 임베딩 조회에 쓰는 기본 자료형이야.
  • torch.bool: 마스크에 써.

형변환

.to()는 자료형과 장치를 바꾸는 범용 연산이야. 자료형이나 장치, 또는 둘 다 받을 수 있고 이미 요청한 상태라면 원래 텐서를 그대로 반환해. .float(), .half(), .cpu(), .cuda() 같은 줄임말도 있으니 문맥에 더 잘 읽히는 쪽을 쓰면 돼.

Code

세 가지 정체성 읽기·python
import torch

t = torch.randn(8, 3, 224, 224, device="cpu")

print(t.shape)    # torch.Size([8, 3, 224, 224])
print(t.size())   # same thing — both shape and size() exist
print(t.ndim)     # 4
print(t.numel())  # 8*3*224*224 = 1,204,224

print(t.dtype)    # torch.float32
print(t.device)   # cpu
print(t.layout)   # torch.strided (contiguous memory, default)
.to()와 줄임말로 형변환·python
import torch

t = torch.randn(3, 3)

# dtype only
t_half = t.half()                  # → float16
t_bf16 = t.bfloat16()              # → bfloat16
t_long = t.long()                  # → int64
t_float64 = t.to(torch.float64)    # → double

# device only
t_gpu = t.to("cuda")               # if available
t_cpu = t_gpu.to("cpu")
t_mps = t.to("mps")                # Apple Silicon

# both at once
t_gpu_half = t.to("cuda", dtype=torch.float16)

# Critically: .to() is a NO-OP if already in the requested form,
# so it's safe to call defensively.
assert t.to(t.dtype, t.device) is not None
자료형 불일치 = 에러: 경계에서 해결·python
import torch
import torch.nn as nn

# A common bug: float64 data colliding with a float32 model.
data = torch.tensor([[1.0, 2.0]], dtype=torch.float64)
linear = nn.Linear(2, 4)  # weights are float32 by default
# linear(data)  # RuntimeError: expected scalar type Float but got Double

# The fix at the boundary — once, where data enters the model
data = data.to(dtype=torch.float32)
out = linear(data)
print(out.shape)  # torch.Size([1, 4])

External links

Exercise

이전에 학습한 모델을 쓰거나 3계층 MLP를 만들어. 모델 매개변수, 최적화 도구 상태, 배치 입력 하나, 손실의 자료형을 각각 출력하고 서로 맞는지 확인해. 그런 다음 입력을 float64로 바꿔 오류 메시지를 자세히 읽어 봐. 실전에서도 같은 오류를 자주 만나게 될 거야.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.