C.W.K.
Stream
Lesson 03 of 11 · published

shape, dtype, device — 세 숫자

~12 min · dtype, device, shape, metadata

Level 0Tensor 호기심
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

모든 tensor 가 세 조각의 정체성을 들고 있어

print(t) 하면 PyTorch 는 값을 보여줘. 뭔가 깨지면 값은 거의 안 중요해 — metadata 가 중요해. 디버깅 중요도 순서로 세 attribute:

  1. shape — 차원. 어떤 에러든 첫 체크.
  2. dtype — element type. 두 번째 체크, 특히 mixed-precision training.
  3. device — data 가 물리적으로 사는 곳. 'expected cuda:0 got cpu' 에러.

dtype family 는 외워둬야 해 — mixed-precision training 이 진지한 작업의 default 가 됐으니까:

  • torch.float32 (alias torch.float) — activation 과 weight 의 universal default.
  • torch.float16 (alias torch.half) — 메모리 절반, bandwidth 절반, 근데 좁은 dynamic range 라 GradScaler 필요.
  • torch.bfloat16 — float32 와 같은 exponent range, mantissa 정밀도가 덜함. Ampere+ GPU 와 Apple Silicon 의 modern mixed-precision dtype. GradScaler 보통 불필요.
  • torch.float64 (double) — 완전 정밀도. 과학 계산이나 수치 문제 의심될 때 사용, training default 절대 아님.
  • torch.int64 (long) — class label, index, embedding lookup 의 default.
  • torch.bool — mask.

casting

.to() 가 universal mover/caster. dtype, device, 또는 둘 다 받고, 이미 요청 형태면 no-op. shorthand 도 있어 (.float(), .half(), .cpu(), .cuda()) — context 에 따라 더 깔끔한 거 써.

Code

세 가지 정체성 read·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() 와 shorthand 로 cast·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
dtype mismatch = 에러 — 경계에서 fix·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

이전에 train 한 model (또는 3-layer MLP 만들기). 다음의 dtype 출력: model parameter, optimizer state, single batch input, loss. 모두 같은 dtype 인지 확인. 그 다음 input 을 float64 로 cast 하고 에러 메시지 관찰 — 자세히 읽어. 같은 에러가 야생에서 떠.

Progress

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

댓글 0

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

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