시작하기
설치와 텐서
PyTorch 텐서가 핵심 자료구조입니다. to(device)로 텐서를 GPU로 옮기세요. torch.randn이 정규 분포의 랜덤 수를 반환합니다. CUDA 버전에 맞는 올바른 wheel URL을 고르고, 개발용으로는 CPU 전용 빌드가 더 작습니다.
# install PyTorch (CUDA 11.8)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
import torch
# create a tensor
x = torch.tensor([[1, 2], [3, 4]])
y = torch.zeros(3, 3)
z = torch.randn(2, 3) # standard normal
# tensor on GPU
device = "cuda" if torch.cuda.is_available() else "cpu"
x = x.to(device)텐서 속성
모든 텐서에는 shape, dtype, device 속성이 있습니다. 흔한 dtype: float32(기본), float16, int64, bool. numel()이 요소 총수를 반환합니다. 메모리를 절반으로 줄이고 GPU 계산을 가속하려면 혼합 정밀도에 float16을 고르세요.
x = torch.randn(3, 4, 5)
print(x.shape) # torch.Size([3, 4, 5])
print(x.dtype) # torch.float32
print(x.device) # cpu or cuda:0
print(x.requires_grad) # False
# specify dtype at creation
x = torch.zeros(3, dtype=torch.int64)
x = torch.tensor([1.0, 2.0], dtype=torch.float16)
# check number of elements
print(x.numel()) # 3텐서 생성
torch.zeros/ones/full이 상수 텐서를 만듭니다. 범위 텐서는 arange와 linspace이며, rand는 균등, randn은 정규입니다. randint는 상한을 제외합니다. 재현성을 위해 랜덤 연산 전에 torch.manual_seed(42)를 쓰세요.
# from Python lists
a = torch.tensor([1, 2, 3])
# special tensors
zeros = torch.zeros(2, 3)
ones = torch.ones(2, 3)
eye = torch.eye(3) # identity matrix
full = torch.full((2, 3), 7.0)
# ranges
arange = torch.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = torch.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1.0]
# random
rand = torch.rand(2, 3) # uniform [0, 1)
randn = torch.randn(2, 3) # normal N(0, 1)
randint = torch.randint(0, 10, (3, 3))타입 변환
to(dtype)이 텐서 타입을 변환합니다. 축약은 .float(), .long(), .int(), .bool()입니다. numpy()는 텐서와 메모리를 공유합니다(CPU에서 제로카피). item()이 0차원 텐서에서 단일 Python 스칼라를 추출합니다. GPU 텐서는 numpy() 전에 CPU로 옮겨야 합니다.
x = torch.tensor([1.5, 2.5, 3.5])
# change dtype
y = x.to(torch.int32) # tensor([1, 2, 3])
y = x.int() # shortcut
y = x.float()
y = x.bool()
y = x.long() # int64
# to numpy and back
arr = x.numpy() # shares memory (CPU)
t = torch.from_numpy(arr)
# 0-d tensor to Python scalar
val = x[0].item() # 1.5인덱싱과 슬라이싱
PyTorch 인덱싱이 NumPy를 미러링합니다. 정수 인덱싱은 0차원 텐서를 반환하며(Python 스칼라는 .item()), 불리언 마스크는 결과를 평탄화합니다. LongTensor로의 인덱싱은 첫 차원을 따라 선택합니다. 고급 인덱싱은 복사본을, 기본 슬라이싱은 뷰를 만듭니다.
x = torch.arange(12).reshape(3, 4)
# tensor([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
x[0] # first row
x[1, 2] # element at (1, 2) -> 6
x[:, 1] # second column
x[0:2] # first two rows
x[:, ::2] # every other column
# boolean mask
mask = x > 5
x[mask] # tensor([6, 7, 8, 9, 10, 11])
# index with LongTensor
idx = torch.tensor([0, 2])
x[idx] # rows 0 and 2리셰이핑과 뷰
view에는 연속 메모리가 필요하고 reshape은 항상 동작합니다(필요 시 복사). unsqueeze/squeeze가 크기 1 차원을 더하고/제거합니다. permute가 모든 차원을 재정렬하고 transpose가 둘을 바꿉니다. 평탄화는 reshape(-1)입니다. permute 같은 연산이 텐서를 비연속으로 만들 수 있어 view() 전에 .contiguous()가 필요합니다.
x = torch.arange(12)
# reshape (returns view when possible)
y = x.reshape(3, 4)
y = x.view(3, 4) # only for contiguous tensors
# add/remove dimensions
y = x.unsqueeze(0) # shape (1, 12)
y = x.squeeze() # remove size-1 dims
# transpose / permute
a = torch.randn(3, 4, 5)
b = a.permute(2, 0, 1) # shape (5, 3, 4)
b = a.transpose(0, 1) # swap dims 0 and 1
# flatten
flat = a.flatten() # shape (60,)
flat = a.reshape(-1) # equivalent텐서 연산
산술 연산
산술 연산자(+, -, *, /)는 요소별입니다. 제자리 연산은 _로 끝나며 메모리를 아끼지만 autograd 기록을 무효화하므로 grad가 필요한 텐서에는 피하세요. Broadcasting은 NumPy 규칙을 따릅니다. 후행 차원이 매칭되거나 1로 늘어납니다.
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([4.0, 5.0, 6.0])
# element-wise ops
a + b # tensor([5., 7., 9.])
a * b # tensor([ 4., 10., 18.])
a / b # element-wise division
a ** 2 # tensor([1., 4., 9.])
# in-place (suffix _)
a.add_(1) # a = a + 1, modifies in place
a.mul_(2) # a = a * 2
# scalar ops
a + 10
b * 0.5요소별 수학
요소별 수학은 torch.*와 tensor.* 메서드를 미러링합니다. 클리핑의 PyTorch 이름은 clamp입니다. 수치적으로 안전한 log를 위해 하드코딩된 1e-8 대신 torch.finfo(x.dtype).eps를 쓰세요. 활성 함수는 (nn.ReLU() 같은) nn 모듈로도 모델에 제공됩니다.
x = torch.tensor([-1.0, 0.0, 1.0, 2.0])
torch.abs(x) # absolute value
torch.sqrt(torch.abs(x))
torch.exp(x) # e^x
torch.log(x.abs() + 1e-8)
torch.sin(x)
torch.clamp(x, -0.5, 1.5) # clip values
# activation functions
torch.sigmoid(x) # 1 / (1 + e^-x)
torch.tanh(x)
torch.relu(x) # max(0, x)
# rounding
y = torch.tensor([1.4, 1.5, 2.6])
torch.round(y) # tensor([1., 2., 3.])
torch.floor(y)
torch.ceil(y)축소(Reduction) 연산
축소가 하나 이상의 차원을 접습니다. 축 선택은 dim이며, keepdim=True가 축소된 축을 크기 1로 유지합니다(broadcasting에 결정적). dim을 준 max/min이 (values, indices) 이름 붙은 튜플을 반환합니다. 0차원 텐서를 Python 스칼라로 꺼내는 것은 item()입니다.
x = torch.arange(12).reshape(3, 4).float()
x.sum() # 66.0 (scalar tensor)
x.sum(dim=0) # sum over rows -> shape (4,)
x.sum(dim=1) # sum over columns -> shape (3,)
x.mean(dim=1)
x.max() # returns value tensor
x.max(dim=1) # returns (values, indices)
x.argmin(dim=1) # indices of min along dim
# keep dimensions
x.sum(dim=1, keepdim=True) # shape (3, 1)
# norm
x.norm() # Frobenius norm
x.norm(dim=1) # per-row norm비교 연산
비교 연산자가 bool 텐서를 반환합니다. torch.equal은 정확한 동등성을 검사해 Python bool을 반환합니다. torch.where(cond, x, y)가 벡터화된 삼항식으로 마스킹이나 선택에 완벽합니다. topk가 값과 인덱스를 모두 반환하며 top-1 / top-5 정확도에 유용합니다.
a = torch.tensor([1, 2, 3, 4])
b = torch.tensor([3, 2, 1, 4])
a == b # tensor([False, True, False, True])
a > b # tensor([False, False, True, False])
a != b
torch.equal(a, b) # False (single bool)
# where: pick from two tensors
torch.where(a > b, a, b) # element-wise max
# boolean helpers
(a > 2).any() # True
(a > 2).all() # False
(a == b).sum() # 2 (count of True)
# top-k
torch.topk(a, 2) # returns top 2 values + indices행렬 연산
@와 torch.matmul이 행렬 곱을 하며 배치 차원에 broadcasting합니다. 엄격한 3D 배치 matmul(브로드캐스팅 없음)에는 torch.bmm을 쓰세요. einsum이 다중 텐서 수축에 표현력이 좋지만 일부 하드웨어에서 matmul보다 느릴 수 있습니다. 행렬 역행렬은 피하고 torch.solve / linalg.solve로 푸세요.
a = torch.randn(2, 3)
b = torch.randn(3, 4)
# matrix multiplication
c = a @ b # shape (2, 4)
c = torch.matmul(a, b) # equivalent
# batched matmul
A = torch.randn(10, 2, 3)
B = torch.randn(10, 3, 4)
C = A @ B # shape (10, 2, 4)
# element-wise product
e = a * a # shape (2, 3)
# other ops
torch.inverse(a[:, :3]) # inverse of square slice
torch.det(a[:, :3])
torch.svd(a) # singular value decomposition
torch.einsum('bi,i->b', torch.randn(5,3), torch.randn(3)) # batched dot연결과 스태킹
cat이 기존 축을 따라 텐서를 이어붙이고 stack이 새 축을 더합니다. 청크 크기로 나누는 것은 split, 조각 수로 나누는 것은 chunk입니다. expand가 (메모리 복사 없이) broadcasting된 데이터의 뷰를 만들므로 가능하면 repeat 대신 이것을 쓰세요. repeat가 데이터를 물리적으로 복제합니다.
a = torch.randn(2, 3)
b = torch.randn(2, 3)
# concat along existing dim
c = torch.cat([a, b], dim=0) # shape (4, 3)
c = torch.cat([a, b], dim=1) # shape (2, 6)
# stack along new dim
s = torch.stack([a, b], dim=0) # shape (2, 2, 3)
# split / chunk
x = torch.arange(6).reshape(2, 3)
parts = torch.split(x, 2, dim=0) # split into chunks of size 2
chunks = torch.chunk(x, 3, dim=1) # split into 3 chunks
# repeat / expand
r = a.repeat(2, 3) # repeat whole tensor
e = a.unsqueeze(0).expand(4, 2, 3) # broadcast without copyAutograd
기본 Autograd
requires_grad=True로 autograd 추적을 켜세요. 스칼라 텐서에 .backward()를 호출하면 requires_grad=True인 모든 리프 텐서에 대해 그 텐서의 그래디언트가 계산됩니다. 그래디언트가 .grad에 누적되므로 반복 사이에 optimizer.zero_grad() 또는 x.grad=None을 호출하세요.
import torch
# tensors that require gradient tracking
x = torch.tensor([2.0], requires_grad=True)
y = torch.tensor([3.0], requires_grad=True)
# build a computation graph
z = x * y + x ** 2 # z = xy + x^2
print(z.grad_fn) # <AddBackward0 object>
# backprop
z.backward()
# dz/dx = y + 2x = 3 + 4 = 7
print(x.grad) # tensor([7.])
# dz/dy = x = 2
print(y.grad) # tensor([2.])그래디언트 계산
backward()는 스칼라 출력에서만 동작하며, 텐서는 먼저 sum이나 mean하세요. torch.autograd.grad가 .grad에 저장하지 않고 튜플로 그래디언트를 반환합니다. 라이브러리 안이나 비리프 텐서의 그래디언트가 필요할 때 선호됩니다.
import torch
x = torch.linspace(-3, 3, steps=10, requires_grad=True)
y = torch.sin(x)
# sum needed for backward on non-scalar
y.sum().backward()
print(x.grad) # cos(x)
# gradient w.r.t. intermediate tensor
a = torch.tensor(1.0, requires_grad=True)
b = a * 2
c = b ** 2
grads = torch.autograd.grad(c, a)
print(grads) # (tensor(8.),) dc/da = 4b * 2 = 8그래디언트 추적 비활성화
추론에는 torch.no_grad()로 그래프 생성을 건너뛰어 메모리와 시간을 아끼세요. .detach()는 데이터를 공유하지만 그래프에서 잘려 나온 텐서를 반환하며, 로깅이나 비PyTorch 코드에 텐서 전달에 좋습니다. model.eval()이 (dropout, BN 같은) 레이어를 추론 모드로 바꾸지만 autograd를 끄지는 '않으므로' torch.no_grad()와 결합하세요.
x = torch.tensor([1.0], requires_grad=True)
# option 1: context manager (preferred)
with torch.no_grad():
y = x * 2 # y.requires_grad == False
# option 2: decorator
@torch.no_grad()
def inference(x):
return model(x)
# option 3: detach from graph
y = (x * 2).detach() # y is a new tensor, no grad
# enable grad inside no_grad
with torch.no_grad():
with torch.enable_grad():
z = x * 3 # z requires grad고차 그래디언트
create_graph=True가 그래디언트 자체의 그래프를 유지해 다시 미분할 수 있게 합니다. 그래디언트 패널티(WGAN-GP), 메타러닝, 물리 정보 손실에 유용합니다. 여분의 메모리가 들므로 끝나면 retain_graph=False로 중간 그래프를 해제하세요.
x = torch.tensor(0.5, requires_grad=True)
# first derivative
y = torch.sin(x)
y.backward(create_graph=True)
print(x.grad) # cos(0.5)
# second derivative (gradient of gradient)
x.grad.zero_()
g = torch.autograd.grad(torch.sin(x), x, create_graph=True)[0]
g2 = torch.autograd.grad(g, x)[0]
print(g2) # -sin(0.5)
# practical use: penalize gradient (e.g. gradient penalty)
loss = g.norm()그래디언트 훅
텐서의 register_hook로 backward 중 그래디언트를 검사하거나 수정할 수 있습니다. NaN 디버깅이나 특정 텐서의 그래디언트 클리핑 구현에 편리합니다. 모듈의 register_full_backward_hook가 입력과 출력 그래디언트를 모두 봅니다. 변경을 전파하려면 수정된 그래디언트를 항상 반환하세요.
x = torch.tensor([1.0, 2.0], requires_grad=True)
y = (x ** 2).sum()
# full backward hook on a tensor
def print_grad(grad):
print("grad:", grad)
return grad * 2 # can modify gradient
y.register_hook(print_grad)
y.backward()
print(x.grad) # 2x but doubled by hook
# module hook
def hook_fn(module, grad_input, grad_output):
print(module.__class__.__name__, grad_output)
model.layer.register_full_backward_hook(hook_fn)계산 그래프 상세
리프 텐서는 사용자가 만든 것입니다(requires_grad=True, grad_fn 없음). 중간 결과는 비리프입니다. 기본적으로 그래프는 backward() 후 해제되며 여러 번 backward를 호출하려 retain_graph=True를 전달하세요. create_graph=True가 고차 도함수를 위해 그래디언트 그래프를 유지합니다. 메모리가 빠르게 늘어나므로 반복 사이에 x.grad=None으로 지우세요.
x = torch.tensor(2.0, requires_grad=True)
w = torch.tensor(3.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)
y = w * x + b
print(y.is_leaf) # False
print(x.is_leaf) # True
# retain graph for multiple backward passes
loss = (y - 5) ** 2
loss.backward(retain_graph=True)
# can call backward again
loss.backward()
# double backward
loss.backward(create_graph=True)
print(x.grad)데이터 로딩
Dataset과 DataLoader
DataLoader가 Dataset을 배칭, 셔플, 병렬 로드합니다. num_workers>0는 서브프로세스를 쓰며 GPU당 2~8을 설정하세요. CPU→GPU 전송 가속은 pin_memory=True입니다. RAM에 들어가는 작은 데이터셋에는 오버헤드를 피하려 num_workers=0으로 두세요.
from torch.utils.data import Dataset, DataLoader
# built-in datasets
from torchvision import datasets
mnist = datasets.MNIST("./data", train=True, download=True)
# wrap in DataLoader
loader = DataLoader(
mnist,
batch_size=64,
shuffle=True,
num_workers=4,
pin_memory=True,
)
for x, y in loader:
print(x.shape, y.shape) # (64, 1, 28, 28), (64,)
break배치 샘플링
batch_sampler를 전달하면 각 배치를 이루는 인덱스를 정확히 제어합니다. WeightedRandomSampler가 희귀 클래스를 과대표집해 불균형 클래스를 재조정합니다. drop_last=True가 마지막 짧은 배치를 버리며 BatchNorm 안정성에 중요합니다. 샘플러가 인덱스를 순회하면 실제 데이터는 DataLoader가 가져옵니다.
from torch.utils.data import DataLoader, BatchSampler, RandomSampler
dataset = list(range(100))
sampler = RandomSampler(dataset)
batch_sampler = BatchSampler(sampler, batch_size=10, drop_last=True)
loader = DataLoader(dataset, batch_sampler=batch_sampler)
# custom sampler
class EvenSampler:
def __init__(self, data): self.data = data
def __iter__(self): return iter(range(0, len(self.data), 2))
def __len__(self): return len(self.data) // 2
# weighted sampling for imbalanced classes
from torch.utils.data import WeightedRandomSampler
weights = [0.1] * 50 + [1.0] * 50
sampler = WeightedRandomSampler(weights, num_samples=100)셔플과 샘플링
shuffle=True가 에포크마다 순서를 무작위화합니다(학습에 좋음). 재현 가능한 지표를 위해 검증은 shuffle=False로 유지하세요. random_split이 편리하지만 RNG를 직접 시드할 수 없으므로 완전한 제어에는 torch.randperm과 Generator로 Subset을 쓰세요. Subset은 얇은 인덱스 뷰일 뿐이며 데이터 복사가 없습니다.
from torch.utils.data import DataLoader, random_split
# train/val split
train, val = random_split(dataset, [80, 20])
train_loader = DataLoader(train, batch_size=16, shuffle=True)
val_loader = DataLoader(val, batch_size=32, shuffle=False)
# reproducible split
from torch.utils.data import Subset
import numpy as np
gen = torch.Generator().manual_seed(42)
idx = torch.randperm(len(dataset), generator=gen).tolist()
train_idx, val_idx = idx[:80], idx[80:]
train, val = Subset(dataset, train_idx), Subset(dataset, val_idx)커스텀 Collate
collate_fn이 샘플 목록을 배치로 만듭니다. 기본은 새 dim 0을 따라 텐서를 쌓습니다. 가변 길이 시퀀스(pack_padded_sequence를 위해 패딩 후 길이순 정렬), dict 기반 샘플, 텐서/비텐서 혼합 데이터에는 재정의하세요. 함수를 저렴하게 유지하세요. 데이터 로딩 워커에서 실행됩니다.
from torch.utils.data import default_collate
# variable-length sequences: pad in collate
def pad_collate(batch):
# batch is list of (tensor, label)
seqs, labels = zip(*batch)
lens = torch.tensor([len(s) for s in seqs])
max_len = lens.max()
padded = torch.zeros(len(seqs), max_len)
for i, s in enumerate(seqs):
padded[i, :len(s)] = s
return padded, lens, torch.tensor(labels)
loader = DataLoader(dataset, batch_size=4, collate_fn=pad_collate)
# stack batch as dict
def dict_collate(batch):
return default_collate(batch)병렬 로딩
num_workers가 데이터 로딩을 병렬화해 GPU가 기다리지 않게 합니다. 에포크별 워커 시작 비용 회피는 persistent_workers=True이고, 워커가 미리 준비하는 배치 수는 (기본 2의) prefetch_factor가 제어합니다. Windows와 Jupyter에서 multiprocessing은 불안정할 수 있으니 디버깅은 num_workers=0으로 폴백하세요. 주의: 각 워커가 (열린 파일 핸들과 CUDA 컨텍스트 포함) 전체 프로세스 상태를 물려받습니다.
loader = DataLoader(
dataset,
batch_size=128,
num_workers=8, # one process per worker
pin_memory=True, # page-locked memory for fast H2D copy
persistent_workers=True, # keep workers alive across epochs
prefetch_factor=4, # batches prefetched per worker
)
# avoid CPU bottleneck
import os
os.cpu_count() # check available cores
# in Jupyter / Windows: set start method
import torch.multiprocessing as mp
# mp.set_start_method('spawn') # uncomment if needednn.Module
모듈 정의
nn.Module을 서브클래싱하고 forward()를 구현하세요. 서브 모듈과 파라미터를 속성으로 선언하면 자동 등록됩니다(.to(device), .parameters(), state_dict를 가능하게 하는 것). 항상 super().__init__()을 호출하세요. forward에는 임의의 Python 로직을 넣지 말고 미분 가능하고 텐서 전용으로 유지하세요.
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, in_dim, hidden, out_dim):
super().__init__()
self.fc1 = nn.Linear(in_dim, hidden)
self.fc2 = nn.Linear(hidden, hidden)
self.fc3 = nn.Linear(hidden, out_dim)
self.act = nn.ReLU()
def forward(self, x):
x = self.act(self.fc1(x))
x = self.act(self.fc2(x))
return self.fc3(x) # logits
model = MLP(784, 128, 10)
print(model) # prints structureLinear와 활성 레이어
nn.Linear가 y = xW^T + b를 적용합니다. 가중치 형상은 (out, in)입니다. (state_dict, 훅에) 등록하려면 활성 모듈을 선호하고 일회성 연산에는 functional F.*를 쓰세요. 트랜스포머 아키텍처는 GELU와 SwiGLU식 활성이 지배합니다. Softmax는 보통 모델에서 생략하고 CrossEntropyLoss가 처리하게 합니다.
import torch.nn as nn
linear = nn.Linear(in_features=20, out_features=10, bias=True)
print(linear.weight.shape) # (10, 20)
print(linear.bias.shape) # (10,)
# common activations
nn.ReLU() # max(0, x)
nn.LeakyReLU(0.01)
nn.GELU() # smooth, used in transformers
nn.Sigmoid() # (0, 1)
nn.Tanh() # (-1, 1)
nn.Softmax(dim=1)
nn.ELU()
# functional API (no parameters)
import torch.nn.functional as F
out = F.relu(linear(x)) # same as nn.ReLU()(linear(x))파라미터와 서브모듈
named_parameters()가 전체 트리에 대해 (name, tensor)를 산출하며 고정, 가중치 감쇠, 디버깅에 좋습니다. .modules()가 자식을 재귀하고 .children()은 한 수준뿐입니다. 버퍼(예: BatchNorm running stats)는 state_dict에는 나타나지만 parameters()에는 없으며 확인은 named_buffers()입니다.
model = MLP(784, 128, 10)
# iterate parameters
for name, p in model.named_parameters():
print(name, p.shape, p.requires_grad)
# only trainable params
trainable = filter(lambda p: p.requires_grad, model.parameters())
# count parameters
n_params = sum(p.numel() for p in model.parameters())
print(f"{n_params:,} parameters")
# access submodules by name
model.fc1 # the Linear layer
model['fc1'] # equivalent if using nn.ModuleDict
# children vs modules
list(model.children()) # direct children
list(model.modules()) # recursively all sub-modulesSequential 모델
nn.Sequential이 각 출력이 다음 입력을 먹는 모듈을 사슬로 잇습니다. 선형 파이프라인에 완벽합니다. 속성으로 인덱싱하려(model.fc1) 단계에 이름을 붙이는 OrderedDict를 쓰세요. 분기, 스킵 연결, 다중 입력/출력 모델은 nn.Module을 서브클래싱해 forward()를 명시적으로 쓰세요.
import torch.nn as nn
# simple stack
model = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(256, 10),
)
# named layers via OrderedDict
from collections import OrderedDict
model = nn.Sequential(OrderedDict([
('fc1', nn.Linear(784, 256)),
('relu', nn.ReLU()),
('dropout', nn.Dropout(0.5)),
('fc2', nn.Linear(256, 10)),
]))
print(model.fc1) # access by name
# append at runtime
model.append(nn.Softmax(dim=1))모듈 메서드
to(device)가 파라미터와 버퍼를 옮기고 .double()/.half()/.float()가 dtype을 캐스팅합니다. train()/eval()이 self.training 플래그를 토글하며 Dropout과 BatchNorm이 이에 따라 분기합니다. state_dict()가 모든 파라미터와 버퍼의 OrderedDict를 반환하고 load_state_dict가 복원합니다. .apply(fn)이 모든 서브모듈을 재귀하며 커스텀 초기화에 유용합니다.
model = MLP(784, 128, 10)
# move to device / dtype
model = model.to('cuda')
model = model.to(torch.float16)
# train vs eval mode
model.train() # enable dropout, update BN stats
model.eval() # disable dropout, freeze BN stats
# state dict
sd = model.state_dict()
model.load_state_dict(sd)
# apply a function to all submodules
model.apply(lambda m: print(type(m).__name__))
# set requires_grad on all parameters
for p in model.parameters():
p.requires_grad_(False)초기화
PyTorch는 Linear/Conv에 기본으로 Kaiming He 초기화를 쓰며 대부분의 경우 동작합니다. torch.nn.init 함수로 재정의하세요(접미사 _는 제자리). Kaiming은 ReLU 계열, Xavier/Glorot은 tanh/sigmoid에 맞습니다. 편향 0 초기화가 표준입니다. .apply(fn)이 모든 서브모듈에 fn을 실행해 대량 초기화나 가중치 리셋에 완벽합니다.
import torch.nn as nn
import torch.nn.init as init
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(100, 50)
self.fc2 = nn.Linear(50, 10)
self._init_weights()
def _init_weights(self):
init.kaiming_normal_(self.fc1.weight, nonlinearity='relu')
init.zeros_(self.fc1.bias)
init.xavier_uniform_(self.fc2.weight)
init.zeros_(self.fc2.bias)
# apply to existing model
def init_all(m):
if isinstance(m, nn.Linear):
init.kaiming_normal_(m.weight)
if m.bias is not None:
init.zeros_(m.bias)
model.apply(init_all)손실 함수
CrossEntropyLoss
CrossEntropyLoss가 내부에서 log-softmax + NLLLoss를 적용하므로 원시 로짓을 전달하세요. 소프트맥스 출력은 절대 아닙니다. 타깃은 정수 클래스 인덱스이며(원-핫 아님) 불균형 클래스 에는 weight, 패딩 토큰 마스킹에는 ignore_index=-100입니다. 분류와 NLP의 인기 정규화는 label_smoothing=0.1입니다.
import torch
import torch.nn as nn
# logits shape (N, C), targets shape (N,) with class indices
logits = torch.randn(4, 3) # 4 samples, 3 classes
targets = torch.tensor([0, 2, 1, 0])
criterion = nn.CrossEntropyLoss()
loss = criterion(logits, targets)
# equivalently, combine LogSoftmax + NLLLoss
log_softmax = nn.LogSoftmax(dim=1)
nll = nn.NLLLoss()
loss2 = nll(log_softmax(logits), targets)
# weight classes (handle imbalance)
weights = torch.tensor([1.0, 2.0, 1.0])
criterion = nn.CrossEntropyLoss(weight=weights)
# ignore padding index (NLP)
criterion = nn.CrossEntropyLoss(ignore_index=-100)MSELoss와 L1Loss
MSELoss가 큰 오류를 이차적으로 벌주며(이상값에 민감) L1은 선형으로 더 강건합니다. SmoothL1Loss는 0 근처에서 L2, 멀리서 L1처럼 동작하며 객체 검출(Fast R-CNN)에 쓰입니다. reduction='none'이 요소별 텐서를 반환하므로 .mean() 전에 직접 마스크하거나 가중할 수 있습니다.
import torch.nn as nn
pred = torch.randn(4, 1)
target = torch.randn(4, 1)
# mean squared error (L2)
mse = nn.MSELoss()
loss = mse(pred, target) # mean over all elements
# L1 (mean absolute error)
l1 = nn.L1Loss()
loss = l1(pred, target)
# smooth L1 (Huber) — robust to outliers
smooth = nn.SmoothL1Loss(beta=0.1)
# reduction options
mse_sum = nn.MSELoss(reduction='sum')
mse_none = nn.MSELoss(reduction='none') # per-elementBCELoss와 BCEWithLogitsLoss
BCELoss+sigmoid보다 항상 BCEWithLogitsLoss를 선호하세요. 수치 안정성을 위해 log-sum-exp 트릭을 씁니다. pos_weight가 (포컬 로스 라이트처럼) 클래스 불균형을 상쇄하려 양성 항을 곱합니다. (각 클래스 독립인) 멀티 레이블 분류에는 (N, C) 형상과 sigmoid 출력으로 BCEWithLogitsLoss를 쓰세요.
import torch.nn as nn
# binary classification, multi-label, or sigmoid outputs
logits = torch.randn(4, 1)
target = torch.tensor([[1.0], [0.0], [1.0], [0.0]])
# preferred: combines sigmoid + BCE, numerically stable
criterion = nn.BCEWithLogitsLoss()
loss = criterion(logits, target)
# BCELoss expects probabilities (apply sigmoid first)
criterion = nn.BCELoss()
probs = torch.sigmoid(logits)
loss = criterion(probs, target)
# positive weight for imbalanced binary tasks
pos_weight = torch.tensor([5.0])
criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)커스텀 손실 함수
커스텀 손실은 스칼라 텐서를 반환하는 함수(또는 nn.Module)일 뿐이며 autograd가 나머지를 처리합니다. 모 든 연산을 미분 가능하게 하세요(서로 다른 미분 가능 분기의 torch.where는 괜찮음). 하이퍼파라미터, 직렬화, 설정 등록이 필요하면 모듈 형태가 선호됩니다. 동작 예측을 위해 reduction(mean/sum/none)을 명시하세요.
import torch
import torch.nn as nn
import torch.nn.functional as F
# as a function
def huber_loss(pred, target, delta=1.0):
error = pred - target
abs_err = error.abs()
quad = torch.where(abs_err <= delta,
0.5 * error ** 2,
delta * (abs_err - 0.5 * delta))
return quad.mean()
# as a module (so it can have parameters / state)
class FocalLoss(nn.Module):
def __init__(self, alpha=0.25, gamma=2.0):
super().__init__()
self.alpha = alpha
self.gamma = gamma
def forward(self, logits, targets):
bce = F.binary_cross_entropy_with_logits(logits, targets, reduction='none')
p = torch.sigmoid(logits)
pt = p * targets + (1 - p) * (1 - targets)
loss = self.alpha * (1 - pt) ** self.gamma * bce
return loss.mean()
criterion = FocalLoss()손실 축소와 결합
reduction='none'이 샘플별 손실을 주어 수동 마스킹, 재가중, 집계가 가능합니다. 멀티태스크 손실 결합은 가중 합이며 가중치가 크기가 아니라 그래디언트의 균형을 잡습니다(튜닝하세요). 각 하위 손실은 미분 가능하고 같은 디바이스/dtype이어야 합니다. 역전파 없이 로그하려 .detach()로 손실 항을 떼세요.
import torch.nn as nn
import torch
criterion = nn.CrossEntropyLoss(reduction='none')
loss_per = criterion(logits, targets) # shape (N,)
loss = loss_per.mean()
# class-wise mask
mask = targets != -100
loss = criterion(logits[mask], targets[mask])
# multi-task loss
loss_cls = nn.CrossEntropyLoss()(logits, labels)
loss_box = nn.L1Loss()(boxes_pred, boxes_gt)
total = 1.0 * loss_cls + 0.5 * loss_box
# gradient-weighted
total = loss_cls + 0.5 * loss_box
total.backward()NLLLoss와 기타 손실
NLLLoss + LogSoftmax가 수학적으로 CrossEntropyLoss와 동일하지만 로그 확률을 재사용하게 합니다. 메트릭 러닝 임베딩 학습은 TripletMarginLoss입니다. KLDivLoss는 입력에 로그 확률, 타깃에 확률을 기대합니다. 미분할되지 않은 시퀀스를 타깃에 정렬하는 것은 CTCLoss이며 런타임 오류를 피하려 input_lengths와 target_lengths를 전달하세요.
import torch.nn as nn
# NLLLoss expects log-probabilities (use LogSoftmax first)
log_probs = torch.log_softmax(logits, dim=1)
loss = nn.NLLLoss()(log_probs, targets)
# triplet loss for embeddings
anchor = torch.randn(4, 128)
positive = torch.randn(4, 128)
negative = torch.randn(4, 128)
loss = nn.TripletMarginLoss(margin=1.0)(anchor, positive, negative)
# KL divergence (distributions)
loss = nn.KLDivLoss(reduction='batchmean')(log_probs, target_dist)
# cosine embedding loss
loss = nn.CosineEmbeddingLoss()(x1, x2, torch.tensor([1, -1, 1, -1]))
# CTCLoss for sequence alignment (ASR/OCR)
loss = nn.CTCLoss(blank=0, zero_infinity=True)(log_probs, targets, in_lens, out_lens)옵티마이저
SGD
SGD + momentum이 여전히 대배치 CNN 학습의 최상위 선택이며 일부 작업에서 Adam보다 더 잘 일반화합니다. momentum 0.9가 표준이고 Nesterov가 작은 추가 이득을 줍니다. L2 정규화는 weight_decay입니다. SGD는 신중한 LR 스케줄링과 워밍업이 필요하며 Adam처럼 자동 튜닝되지 않습니다.
import torch.optim as optim
# basic SGD
optimizer = optim.SGD(model.parameters(), lr=0.01)
# SGD with momentum (classic: 0.9)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
# Nesterov momentum
optimizer = optim.SGD(
model.parameters(),
lr=0.01,
momentum=0.9,
nesterov=True,
)
# weight decay (L2 regularization)
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)Adam과 AdamW
Adam이 파라미터별 모멘트를 저장해 스텝 크기를 자동 적응시키므로 NLP와 작은 데이터셋의 훌륭한 기본값입니다. AdamW가 가중치 감쇠를 그래디언트 갱신에서 분리하며 규모에서(트랜스포머) 중요합니다. betas=(0.9, 0.999)가 표준이며 일부 비전 모델은 (0.9, 0.95)를 씁니다. 전이 학습에서 서로 다른 학습률은 파라미터 그룹별로 쓰세요.
import torch.optim as optim
# Adam — adaptive, default-friendly
optimizer = optim.Adam(model.parameters(), lr=1e-3)
# AdamW — decoupled weight decay (preferred for transformers)
optimizer = optim.AdamW(
model.parameters(),
lr=3e-4,
betas=(0.9, 0.999),
weight_decay=0.01,
)
# per-parameter group settings
optimizer = optim.Adam([
{'params': model.encoder.parameters(), 'lr': 1e-4},
{'params': model.head.parameters(), 'lr': 1e-3},
], lr=1e-3)옵티마이저 스텝 패턴
3단계 패턴(zero_grad, backward, step)이 PyTorch 학습의 심장입니다. set_to_none=True(최신 버전 기본)가 memset을 건너뛰고 옵티마이저가 파라미터를 건너뛰게 하므로 0 채우기보다 빠릅니다. 클리핑이나 커스텀 갱신은 backward()와 step() 사이에 p.grad.data를 수동 편집하세요.
optimizer = optim.Adam(model.parameters(), lr=1e-3)
# standard training step
optimizer.zero_grad() # clear old grads
loss = criterion(model(x), y)
loss.backward() # compute gradients
optimizer.step() # update parameters
# set gradients to None (faster, recommended)
optimizer.zero_grad(set_to_none=True)
# manual gradient modification
for p in model.parameters():
if p.grad is not None:
p.grad.data.clamp_(-1, 1) # gradient clipping
optimizer.step()그래디언트 클리핑
clip_grad_norm_은 전역 L2 노름이 max_norm을 넘으면 그래디언트를 재스케일합니다. RNN과 트랜스포머의 안정적 기본값입니다. clip_grad_value_가 각 요소를 하드 클램프합니다(덜 흔함). 클리핑이 방향을 바꾸지 않고 폭주 그래디언트를 막습니다. 불안정 조기 감지를 위해 클립 전 grad norm을 로그하세요(>100의 급스파이크는 문제).
# gradient norm clipping (most common)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
# gradient value clipping
torch.nn.utils.clip_grad_value_(model.parameters(), clip_value=0.5)
# in a training loop
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
# inspect gradient norm
total_norm = torch.norm(torch.stack([
p.grad.norm(2) for p in model.parameters() if p.grad is not None
]), 2)학습률과 스케줄
각 param_group이 자기 lr을 가지므로 모두 설정하려 순회하세요. 수동 워밍업이 처음 N 스텝 동안 LR을 선형으로 올려 조기 학습을 안정시킵니다(편향 보정 없는 트랜스포머에 결정적). (코사인 감쇠, OneCycle 등의) 스케줄러 객체는 다음 섹션이며 문서가 달리 말하지 않는 한 항상 optimizer.step() 후 스케줄러를 step하세요.
import torch.optim as optim
# get / set learning rate
for g in optimizer.param_groups:
print(g['lr'])
g['lr'] = 1e-4
# manual warmup
for step in range(warmup_steps):
lr = base_lr * (step + 1) / warmup_steps
for g in optimizer.param_groups:
g['lr'] = lr
# optimizer also accepts schedulers (see lr-scheduler section)
from torch.optim.lr_scheduler import StepLR
scheduler = StepLR(optimizer, step_size=10, gamma=0.1)기타 옵티마이저
RMSprop이 고전 RNN 옵티마이저이며 여전히 잘 동작합니다. Adagrad가 제곱 그래디언트를 누적해 조기 정체할 수 있습니다. 희소 피처에는 괜찮지만 깊은 네트워크에는 아닙니다. LBFGS는 closure와 전배치 평가가 필요하며 작은 볼록 문제나 파인튜닝에 좋지만 큰 깊은 네트워크에는 너무 느립니다. 대부분의 새 프로젝트는 AdamW로 시작하세요.
import torch.optim as optim
# RMSprop — good for RNNs
optim.RMSprop(model.parameters(), lr=1e-3, alpha=0.99)
# Adagrad — adapts per-parameter, accumulates squared grads
optim.Adagrad(model.parameters(), lr=1e-2)
# Adadelta — Adagrad variant with running average
optim.Adadelta(model.parameters(), rho=0.9)
# LBFGS — full-batch quasi-Newton, second-order
optim.LBFGS(model.parameters(), lr=1.0, max_iter=20)
# NAdam — Nesterov-accelerated Adam
optim.NAdam(model.parameters(), lr=1e-3)학습 루프
기본 학습 루프
최소 학습 루프: zero_grad, forward, loss, backward, step. (num_workers와 비동기 겹치며) 데이터는 루프 안에서 GPU로 옮기세요. loss.item()이 스칼라를 Python으로 꺼내며 로깅용으로 하세요. loss 텐서 자체에 하면 그래프가 깨집니다. 재사용을 위해 루프를 함수로 감싸세요.
model = MLP(784, 128, 10).to(device)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
for epoch in range(epochs):
model.train()
for x, y in train_loader:
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
logits = model(x)
loss = criterion(logits, y)
loss.backward()
optimizer.step()
print(f"epoch {epoch}, loss={loss.item():.4f}")루프 안 검증
model.eval() + torch.no_grad()가 둘 다 필요합니다. eval이 dropout/BN을 바꾸고 no_grad가 그래프를 건너뜁니다. 마지막 짧은 배치에서도 평균이 올바르도록 (배치 크기를 곱해) 가중 손실을 누적하세요. 예측 클래스 인덱스는 argmax(dim=1)입니다. 검증 지표가 개선되면 최선 모델을 저장하세요(저장-로드 섹션 참고).
for epoch in range(epochs):
model.train()
for x, y in train_loader:
# ... training step ...
# validation
model.eval()
val_loss, correct, total = 0.0, 0, 0
with torch.no_grad():
for x, y in val_loader:
x, y = x.to(device), y.to(device)
logits = model(x)
val_loss += criterion(logits, y).item() * x.size(0)
correct += (logits.argmax(1) == y).sum().item()
total += x.size(0)
print(f"val_loss={val_loss/total:.4f}, acc={correct/total:.4f}")그래디언트 누적
그래디언트 누적이 스텝 전 여러 미니 배치에 걸쳐 그래디언트를 합산해 더 큰 배치를 시뮬레이트합니다. 실효 그래디언트가 단일 대배치와 일치하도록 손실을 accum_steps로 나누세요. 데이터셋 길이가 accum_steps로 나누어 떨어지게 하거나 에포크 끝에 남은 그래디언트로 스텝하세요. 단일 GPU의 트랜스포머 파인튜닝에 특히 유용합니다.
accum_steps = 4
optimizer.zero_grad()
for i, (x, y) in enumerate(train_loader):
x, y = x.to(device), y.to(device)
loss = criterion(model(x), y) / accum_steps
loss.backward()
if (i + 1) % accum_steps == 0:
optimizer.step()
optimizer.zero_grad()
# equivalent effective batch = accum_steps * batch_size
# useful when GPU memory limits batch size혼합 정밀도 학습
혼합 정밀도가 forward 연산을 (Ampere+에서는 bfloat16으로) float16으로 실행해 1.5~3배 가속과 메모리 절반을 얻습니다. GradScaler가 float16 그래디언트 언더플로를 막으려 손실을 곱한 뒤 optimizer.step() 전에 언스케일합니다. H100/A100에서는 bfloat16을 선호하세요. float32와 같은 범위이며 스케일러가 필요 없습니다. autocast 컨텍스트 매니저가 forward 패스에만 영향을 줍니다.
from torch.amp import autocast, GradScaler
scaler = GradScaler('cuda')
for x, y in train_loader:
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
with autocast('cuda'):
logits = model(x)
loss = criterion(logits, y)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
# autocast casts select ops to float16/bf16 for speed
# GradScaler prevents underflow by scaling the loss진행과 로깅
tqdm이 실시간 진행 바를 보여 주며 실행 중 손실 표시는 set_postfix입니다. 지수 이동 평균(running = 0.9*running + 0.1*loss)이 원시 마지막 배치 값보다 노이즈를 더 잘 부드럽게 합니다. 진지한 실행은 stdout 대신 TensorBoard나 Weights & Biases에 로그해 실행을 비교하세요. 학습이 느려진다면 매 스텝 로그를 피하세요.
from tqdm import tqdm
for epoch in range(epochs):
model.train()
pbar = tqdm(train_loader, desc=f"epoch {epoch}")
running = 0.0
for i, (x, y) in enumerate(pbar):
x, y = x.to(device), y.to(device)
optimizer.zero_grad()
loss = criterion(model(x), y)
loss.backward()
optimizer.step()
running = 0.9 * running + 0.1 * loss.item()
pbar.set_postfix(loss=f"{running:.4f}")
# TensorBoard logging (see visualization section)
writer.add_scalar('train/loss', loss.item(), global_step)재현성
완전한 재현성에는 Python, NumPy, PyTorch CPU, CUDA의 seed가 필요합니다. cudnn.deterministic=True가 (일부 conv backward 연산의) 비결정적 알고리즘을 끕니다. DataLoader 워커는 자기 RNG 상태로 fork되므로 worker_init_fn으로 각각 시드해야 합니다. 그래도 멀티 GPU와 일부 cuDNN 연산은 비트 재현이 안 될 수 있으니 통계적 재현성을 겨냥하세요.
import torch, numpy as np, random
def set_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
# cudnn determinism (may slow down)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
set_seed(42)
# DataLoader worker seeding
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
g = torch.Generator().manual_seed(42)
loader = DataLoader(ds, batch_size=32, worker_init_fn=seed_worker, generator=g)평가와 지표
Eval 모드와 No Grad
평가에는 model.eval()과 torch.no_grad()를 항상 짝지으세요. eval()이 dropout과 BatchNorm을 추론 모드로 바꾸고(BN은 running stats 사용) no_grad()가 메모리와 시간을 위해 autograd를 끕니다. 마지막 배치가 짧아도 최종 평균이 편향되지 않도록 누적 시 손실에 배치 크기를 곱하세요.
model.eval()
test_loss, correct, total = 0.0, 0, 0
with torch.no_grad():
for x, y in test_loader:
x, y = x.to(device), y.to(device)
logits = model(x)
test_loss += criterion(logits, y).item() * x.size(0)
preds = logits.argmax(dim=1)
correct += (preds == y).sum().item()
total += x.size(0)
print(f"test_loss={test_loss/total:.4f}, acc={correct/total:.4f}")정확도와 Top-k
argmax(dim=1)가 행별 예측 클래스를 반환합니다. topk가 k개 최대 값과 인덱스를 반환하며, 이를 (N,1)로 확장한 타깃과 비교하고 .any(dim=1)을 쓰면 top-k 정답 여부가 됩니다. 클래스별 정확도가 전체 정확도가 숨기는 불균형 문제를 드러냅니다. print나 log에 넘기기 전 항상 텐서를 CPU로 옮기고 .item()을 호출하세요.
logits = torch.randn(8, 10)
targets = torch.randint(0, 10, (8,))
# top-1 accuracy
preds = logits.argmax(dim=1)
acc = (preds == targets).float().mean().item()
# top-k accuracy
topk = 3
_, idx = logits.topk(topk, dim=1) # shape (N, k)
correct = idx.eq(targets.view(-1, 1)).any(dim=1)
topk_acc = correct.float().mean().item()
# per-class accuracy
for c in range(10):
mask = targets == c
print(c, (preds[mask] == targets[mask]).float().mean().item())혼동 행렬
배치별 동기화를 피하려 예측을 GPU에서 누적한 뒤 마지막에 한 번 CPU로 옮기세요. confusion_matrix가 모델이 어느 클래스를 혼동하는지 보여 주어 디버깅에 완벽합니다. 클래스별 정밀도, 재현율, F1은 classification_report입니다. 매우 큰 데이터셋은 예측을 메모리에 쥐는 대신 디스크로 스트리밍하세요.