Skip to content

PyTorch 치트시트

Meta가 개발한 오픈소스 딥러닝 프레임워크입니다.

01

시작하기

설치와 텐서

PyTorch 텐서가 핵심 자료구조입니다. to(device)로 텐서를 GPU로 옮기세요. torch.randn이 정규 분포의 랜덤 수를 반환합니다. CUDA 버전에 맞는 올바른 wheel URL을 고르고, 개발용으로는 CPU 전용 빌드가 더 작습니다.

pytorch
# 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을 고르세요.

pytorch
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)를 쓰세요.

pytorch
# 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로 옮겨야 합니다.

pytorch
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로의 인덱싱은 첫 차원을 따라 선택합니다. 고급 인덱싱은 복사본을, 기본 슬라이싱은 뷰를 만듭니다.

pytorch
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()가 필요합니다.

pytorch
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
02

텐서 연산

산술 연산

산술 연산자(+, -, *, /)는 요소별입니다. 제자리 연산은 _로 끝나며 메모리를 아끼지만 autograd 기록을 무효화하므로 grad가 필요한 텐서에는 피하세요. Broadcasting은 NumPy 규칙을 따릅니다. 후행 차원이 매칭되거나 1로 늘어납니다.

pytorch
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 모듈로도 모델에 제공됩니다.

pytorch
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()입니다.

pytorch
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 정확도에 유용합니다.

pytorch
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로 푸세요.

pytorch
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가 데이터를 물리적으로 복제합니다.

pytorch
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 copy
03

Autograd

기본 Autograd

requires_grad=True로 autograd 추적을 켜세요. 스칼라 텐서에 .backward()를 호출하면 requires_grad=True인 모든 리프 텐서에 대해 그 텐서의 그래디언트가 계산됩니다. 그래디언트가 .grad에 누적되므로 반복 사이에 optimizer.zero_grad() 또는 x.grad=None을 호출하세요.

pytorch
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에 저장하지 않고 튜플로 그래디언트를 반환합니다. 라이브러리 안이나 비리프 텐서의 그래디언트가 필요할 때 선호됩니다.

pytorch
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()와 결합하세요.

pytorch
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로 중간 그래프를 해제하세요.

pytorch
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가 입력과 출력 그래디언트를 모두 봅니다. 변경을 전파하려면 수정된 그래디언트를 항상 반환하세요.

pytorch
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으로 지우세요.

pytorch
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)
04

데이터 로딩

Dataset과 DataLoader

DataLoader가 Dataset을 배칭, 셔플, 병렬 로드합니다. num_workers>0는 서브프로세스를 쓰며 GPU당 2~8을 설정하세요. CPU→GPU 전송 가속은 pin_memory=True입니다. RAM에 들어가는 작은 데이터셋에는 오버헤드를 피하려 num_workers=0으로 두세요.

pytorch
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가 가져옵니다.

pytorch
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은 얇은 인덱스 뷰일 뿐이며 데이터 복사가 없습니다.

pytorch
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 기반 샘플, 텐서/비텐서 혼합 데이터에는 재정의하세요. 함수를 저렴하게 유지하세요. 데이터 로딩 워커에서 실행됩니다.

pytorch
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 컨텍스트 포함) 전체 프로세스 상태를 물려받습니다.

pytorch
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 needed
05

nn.Module

모듈 정의

nn.Module을 서브클래싱하고 forward()를 구현하세요. 서브 모듈과 파라미터를 속성으로 선언하면 자동 등록됩니다(.to(device), .parameters(), state_dict를 가능하게 하는 것). 항상 super().__init__()을 호출하세요. forward에는 임의의 Python 로직을 넣지 말고 미분 가능하고 텐서 전용으로 유지하세요.

pytorch
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 structure

Linear와 활성 레이어

nn.Linear가 y = xW^T + b를 적용합니다. 가중치 형상은 (out, in)입니다. (state_dict, 훅에) 등록하려면 활성 모듈을 선호하고 일회성 연산에는 functional F.*를 쓰세요. 트랜스포머 아키텍처는 GELU와 SwiGLU식 활성이 지배합니다. Softmax는 보통 모델에서 생략하고 CrossEntropyLoss가 처리하게 합니다.

pytorch
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()입니다.

pytorch
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-modules

Sequential 모델

nn.Sequential이 각 출력이 다음 입력을 먹는 모듈을 사슬로 잇습니다. 선형 파이프라인에 완벽합니다. 속성으로 인덱싱하려(model.fc1) 단계에 이름을 붙이는 OrderedDict를 쓰세요. 분기, 스킵 연결, 다중 입력/출력 모델은 nn.Module을 서브클래싱해 forward()를 명시적으로 쓰세요.

pytorch
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)이 모든 서브모듈을 재귀하며 커스텀 초기화에 유용합니다.

pytorch
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을 실행해 대량 초기화나 가중치 리셋에 완벽합니다.

pytorch
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)
06

손실 함수

CrossEntropyLoss

CrossEntropyLoss가 내부에서 log-softmax + NLLLoss를 적용하므로 원시 로짓을 전달하세요. 소프트맥스 출력은 절대 아닙니다. 타깃은 정수 클래스 인덱스이며(원-핫 아님) 불균형 클래스에는 weight, 패딩 토큰 마스킹에는 ignore_index=-100입니다. 분류와 NLP의 인기 정규화는 label_smoothing=0.1입니다.

pytorch
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() 전에 직접 마스크하거나 가중할 수 있습니다.

pytorch
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-element

BCELoss와 BCEWithLogitsLoss

BCELoss+sigmoid보다 항상 BCEWithLogitsLoss를 선호하세요. 수치 안정성을 위해 log-sum-exp 트릭을 씁니다. pos_weight가 (포컬 로스 라이트처럼) 클래스 불균형을 상쇄하려 양성 항을 곱합니다. (각 클래스 독립인) 멀티 레이블 분류에는 (N, C) 형상과 sigmoid 출력으로 BCEWithLogitsLoss를 쓰세요.

pytorch
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)을 명시하세요.

pytorch
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()로 손실 항을 떼세요.

pytorch
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를 전달하세요.

pytorch
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)
07

옵티마이저

SGD

SGD + momentum이 여전히 대배치 CNN 학습의 최상위 선택이며 일부 작업에서 Adam보다 더 잘 일반화합니다. momentum 0.9가 표준이고 Nesterov가 작은 추가 이득을 줍니다. L2 정규화는 weight_decay입니다. SGD는 신중한 LR 스케줄링과 워밍업이 필요하며 Adam처럼 자동 튜닝되지 않습니다.

pytorch
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)를 씁니다. 전이 학습에서 서로 다른 학습률은 파라미터 그룹별로 쓰세요.

pytorch
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를 수동 편집하세요.

pytorch
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의 급스파이크는 문제).

pytorch
# 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하세요.

pytorch
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로 시작하세요.

pytorch
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)
08

학습 루프

기본 학습 루프

최소 학습 루프: zero_grad, forward, loss, backward, step. (num_workers와 비동기 겹치며) 데이터는 루프 안에서 GPU로 옮기세요. loss.item()이 스칼라를 Python으로 꺼내며 로깅용으로 하세요. loss 텐서 자체에 하면 그래프가 깨집니다. 재사용을 위해 루프를 함수로 감싸세요.

pytorch
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)입니다. 검증 지표가 개선되면 최선 모델을 저장하세요(저장-로드 섹션 참고).

pytorch
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의 트랜스포머 파인튜닝에 특히 유용합니다.

pytorch
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 패스에만 영향을 줍니다.

pytorch
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에 로그해 실행을 비교하세요. 학습이 느려진다면 매 스텝 로그를 피하세요.

pytorch
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 연산은 비트 재현이 안 될 수 있으니 통계적 재현성을 겨냥하세요.

pytorch
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)
09

평가와 지표

Eval 모드와 No Grad

평가에는 model.eval()과 torch.no_grad()를 항상 짝지으세요. eval()이 dropout과 BatchNorm을 추론 모드로 바꾸고(BN은 running stats 사용) no_grad()가 메모리와 시간을 위해 autograd를 끕니다. 마지막 배치가 짧아도 최종 평균이 편향되지 않도록 누적 시 손실에 배치 크기를 곱하세요.

pytorch
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()을 호출하세요.

pytorch
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입니다. 매우 큰 데이터셋은 예측을 메모리에 쥐는 대신 디스크로 스트리밍하세요.

pytorch
from sklearn.metrics import confusion_matrix, classification_report
import numpy as np

all_preds, all_labels = [], []
model.eval()
with torch.no_grad():
    for x, y in test_loader:
        logits = model(x.to(device))
        all_preds.append(logits.argmax(1).cpu())
        all_labels.append(y)

preds = torch.cat(all_preds).numpy()
labels = torch.cat(all_labels).numpy()

cm = confusion_matrix(labels, preds)
print(cm)
print(classification_report(labels, preds))

Precision, Recall, F1

torchmetrics가 배치에 걸쳐 상태를 누적해 클래스 불균형이나 배치 크기 변화가 있어도 지표를 올바르게 계산합니다. average='macro'가 모든 클래스를 동등히 대우하고, 'weighted'가 support로 가중하며, 'micro'는 단일 레이블 작업에서 정확도와 같습니다. 누산기 비우기는 에포크나 평가 사이 .reset()입니다.

pytorch
from torchmetrics import Accuracy, Precision, Recall, F1Score

acc = Accuracy(task='multiclass', num_classes=10).to(device)
prec = Precision(task='multiclass', num_classes=10, average='macro').to(device)
rec = Recall(task='multiclass', num_classes=10, average='macro').to(device)
f1 = F1Score(task='multiclass', num_classes=10, average='macro').to(device)

model.eval()
with torch.no_grad():
    for x, y in test_loader:
        logits = model(x.to(device))
        preds = logits.argmax(1)
        acc.update(preds, y.to(device))
        prec.update(preds, y.to(device))

print(acc.compute(), prec.compute(), f1.compute())

교차 검증

K-fold 교차 검증이 모델 성능과 그 분산의 견고한 추정을 줍니다. 가중치가 fold 간 새지 않도록 fold마다 모델을 재인스턴스화하세요. 큰 데이터셋에는 5 folds가 보통 충분하고, 작은 것에는 (StratifiedKFold 같은) 계층 분할로 클래스 균형을 유지하세요. 안정성이 보이도록 mean +/- std를 보고하세요.

pytorch
from sklearn.model_selection import KFold

kfold = KFold(n_splits=5, shuffle=True, random_state=42)
fold_accs = []

for fold, (train_idx, val_idx) in enumerate(kfold.split(dataset)):
    train = torch.utils.data.Subset(dataset, train_idx)
    val = torch.utils.data.Subset(dataset, val_idx)

    model = build_model()                  # fresh model per fold
    train_model(model, train)              # your training function

    acc = evaluate(model, val)
    fold_accs.append(acc)
    print(f"fold {fold}: acc={acc:.4f}")

print(f"mean={np.mean(fold_accs):.4f} +/- {np.std(fold_accs):.4f}")

모델 비교

모델은 항상 같은 held-out 테스트 셋, 같은 seed, 같은 지표로 비교하세요. 정확도 넘어 캘리브레이션, 추론 지연, 메모리를 보세요. 테스트 셋 차이가 작을 때는 부트스트랩 신뢰 구간을 쓰세요. (CSV나 W&B의) 결과 테이블을 유지하면 마지막 실행이 아니라 미래 실험과 비교할 수 있습니다.

pytorch
results = {}
for name, model in models.items():
    model.eval()
    accs, losses = [], []
    with torch.no_grad():
        for x, y in test_loader:
            x, y = x.to(device), y.to(device)
            logits = model(x)
            losses.append(criterion(logits, y).item())
            accs.append((logits.argmax(1) == y).float().mean().item())
    results[name] = {
        'acc': np.mean(accs),
        'loss': np.mean(losses),
    }

for name, r in sorted(results.items(), key=lambda kv: -kv[1]['acc']):
    print(f"{name:20s} acc={r['acc']:.4f} loss={r['loss']:.4f}")
10

저장과 로드

State Dict 저장과 로드

state_dict()는 파라미터 텐서의 OrderedDict이며 이것(전체 모델이 아니라)을 저장하는 것이 권장 패턴입니다. 이식 가능하고 정확한 클래스/파일 배치와 분리되기 때문입니다. CUDA 체크포인트를 CPU에서 로드하게 하는 것은 map_location입니다. strict=False가 일치하는 키만 로드하며 아키텍처가 살짝 바뀌었을 때 편리합니다.

pytorch
import torch

# save (recommended: only state_dict)
torch.save(model.state_dict(), 'model.pth')

# load
model = MLP(784, 128, 10)        # must match the saved architecture
model.load_state_dict(torch.load('model.pth', map_location='cpu'))
model.eval()

# load on GPU that was trained on GPU
model.load_state_dict(torch.load('model.pth'))
model.to(device)

# strict=False allows partial loading (transfer learning)
model.load_state_dict(torch.load('model.pth'), strict=False)

전체 모델 저장

전체 모델 저장은 Python 객체를 피클해 저장 시점의 정확한 클래스와 파일 구조에 묶습니다. 취약하며 어떤 리팩터든 로딩이 깨집니다. 빠른 실험에만 쓰세요. 배포하거나 공유할 것은 state_dict를 저장하고 아키텍처는 코드나 설정에 두세요.

pytorch
# save entire model (uses pickle) — NOT recommended
torch.save(model, 'model_full.pth')

# load
model = torch.load('model_full.pth', map_location='cpu')
model.eval()

# pickle limitations:
# - class definition must be importable at load time
# - breaks if you refactor or rename the class
# - not portable across PyTorch versions
# prefer state_dict for production

학습 체크포인트

완전 체크포인트가 (모델, 옵티마이저, 스케줄러, 에포크, RNG 상태를 포함) 학습을 정확히 재개하는 데 필요한 모든 것을 저장합니다. 옵티마이저 상태(모멘텀 버퍼, Adam 모멘트)가 필수입니다. 없이 재개하면 사실상 옵티마이저가 재초기화되어 손실이 치솟을 수 있습니다. RNG 상태는 비트 정확 재현이 필요할 때만 저장하세요.

pytorch
checkpoint = {
    'epoch': epoch,
    'model_state': model.state_dict(),
    'optimizer_state': optimizer.state_dict(),
    'scheduler_state': scheduler.state_dict() if scheduler else None,
    'loss': loss.item(),
    'rng_state': torch.get_rng_state(),
    'cuda_rng_state': torch.cuda.get_rng_state_all(),
}
torch.save(checkpoint, f'ckpt_epoch{epoch}.pth')

# resume
ckpt = torch.load('ckpt_epoch10.pth', map_location='cpu')
model.load_state_dict(ckpt['model_state'])
optimizer.load_state_dict(ckpt['optimizer_state'])
start_epoch = ckpt['epoch'] + 1
torch.set_rng_state(ckpt['rng_state'])

최선 모델 저장

검증 지표 기준으로 최선 체크포인트를 저장하면 이후 에포크가 과적합해도 최선 모델을 회복할 수 있습니다. 대부분의 작업에서는 디스크를 위해 최선 체크포인트만 유지하고, 연구에는 롤백을 위해 에포크별 체크포인트를 유지하세요. (epoch, train_loss, val_loss, val_acc, path)의 CSV 로그와 결합하면 어느 체크포인트를 고를지 알 수 있습니다.

pytorch
best_acc = 0.0
for epoch in range(epochs):
    train_one_epoch(model, ...)
    acc = evaluate(model, val_loader)

    if acc > best_acc:
        best_acc = acc
        torch.save(model.state_dict(), 'best.pth')
        print(f"new best {acc:.4f} saved")

# load best at the end
model.load_state_dict(torch.load('best.pth'))
final_acc = evaluate(model, test_loader)

부분 모델 로드

strict=False가 누락 및 예상 밖 키의 목록을 반환하므로 검사해 예상한 레이어만 건너뛰었는지 확인하세요. 키 이름 변경으로 체크포인트를 이름이 바뀐 아키텍처에 적응시킬 수 있습니다. 백본 로드 후에는 순수 피처 추출을 위해 가중치를 고정하거나 새 헤드보다 훨씬 작은 LR로 학습하세요.

pytorch
# transfer learning: load a backbone, drop the classifier
pretrained = torch.load('resnet_backbone.pth')
model = ResNet(num_classes=100)

# drop mismatched keys (e.g. final fc)
missing, unexpected = model.load_state_dict(pretrained, strict=False)
print('missing:', missing)        # e.g. ['fc.weight', 'fc.bias']
print('unexpected:', unexpected)

# rename keys before loading
pretrained = {k.replace('encoder.', 'backbone.'): v
              for k, v in pretrained.items()}

# freeze loaded weights
for name, p in model.named_parameters():
    if 'fc' not in name:
        p.requires_grad_(False)

TorchScript 내보내기

TorchScript가 원래 클래스 없이 LibTorch(C++)나 Python에서 로드할 수 있는 자기 완결 그래프를 만들어 배포에 이상적입니다. trace가 한 제어 흐름 경로를 캡처하고 script는 데이터 의존 제어 흐름을 다루지만 타입 주석이 필요합니다. ONNX Runtime, TensorRT, OpenVINO 추론용 내보내기는 ONNX이며 가변 배치 크기는 dynamic_axes입니다.

pytorch
# scripted (production-ready, runs without Python)
scripted = torch.jit.script(model)
scripted.save('model_scripted.pt')

# traced (records a static graph from sample input)
example = torch.randn(1, 3, 224, 224)
traced = torch.jit.trace(model, example)
traced.save('model_traced.pt')

# load TorchScript in C++ / Python
loaded = torch.jit.load('model_scripted.pt')
loaded.eval()
out = loaded(example)

# export to ONNX (cross-framework)
torch.onnx.export(model, example, 'model.onnx',
                  input_names=['input'],
                  output_names=['output'],
                  dynamic_axes={'input': {0: 'batch'}})
11

CNN

Conv2d 레이어

Conv2d 가중치 형상은 (out_channels, in_channels/groups, kH, kW)입니다. 기본 메모리 배치는 NCHW입니다. stride 1의 공간 크기 유지는 padding='same'(PyTorch 1.9+)입니다. groups=in_channels가 (MobileNet이 쓰는) depthwise로 만듭니다. 출력 크기 계산: (H + 2P - K) / S + 1.

pytorch
import torch.nn as nn

conv = nn.Conv2d(
    in_channels=3,        # RGB input
    out_channels=16,      # number of filters
    kernel_size=3,        # 3x3 filter
    stride=1,
    padding=1,            # 'same' for kernel 3, stride 1
    bias=True,
)
print(conv.weight.shape)   # (16, 3, 3, 3)

x = torch.randn(4, 3, 32, 32)   # NCHW
out = conv(x)
print(out.shape)                # (4, 16, 32, 32) with padding=1

# depthwise separable conv
dw = nn.Conv2d(16, 16, 3, padding=1, groups=16)

풀링 레이어

풀링이 공간 차원을 다운샘플해 작은 이동에 불변성을 더합니다. 가장 강한 응답 유지는 MaxPool, 더 부드러운 것은 AvgPool입니다. 공간 차원을 1x1로 접는 AdaptiveAvgPool2d(1)가 conv 피처를 Linear 헤드로 먹이는 표준 '전역 평균 풀'입니다. 현대 아키텍처에서 학습 가능한 다운샘플링은 풀링보다 스트라이드 conv를 선호하세요.

pytorch
import torch.nn as nn

x = torch.randn(4, 16, 32, 32)

# max pooling
pool = nn.MaxPool2d(kernel_size=2, stride=2)
out = pool(x)              # shape (4, 16, 16, 16)

# average pooling
avg = nn.AvgPool2d(2, stride=2)

# adaptive pool — output size fixed regardless of input
gap = nn.AdaptiveAvgPool2d(1)   # global average pool
out = gap(x)                    # shape (4, 16, 1, 1)

# fractional max pool (slightly improves accuracy)
fmp = nn.FractionalMaxPool2d(2, output_ratio=0.5)

CNN 아키텍처

정석 CNN 블록은 Conv -> BatchNorm -> ReLU -> Pool입니다. AdaptiveAvgPool2d(1)가 네트워크를 입력 크기 무관하게 만들어 한 해상도로 학습하고 다른 해상도로 테스트할 수 있게 합니다. BatchNorm2d는 conv 뒤, 활성 앞에 옵니다. conv 커널은 (VGG 스타일의) 3x3과 padding=1로 유지하세요. 파라미터 효율적이며 융합이 잘 됩니다.

pytorch
import torch.nn as nn

class TinyCNN(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2),                       # 32 -> 16
            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2),                       # 16 -> 8
        )
        self.classifier = nn.Sequential(
            nn.AdaptiveAvgPool2d(1),
            nn.Flatten(),
            nn.Linear(64, num_classes),
        )

    def forward(self, x):
        return self.classifier(self.features(x))

피처 맵과 수용 영역

피처 맵이 각 채널이 무엇을 감지하는지 보여 줍니다. 초창 레이어는 엣지와 색을, 깊은 레이어는 텍스처와 부분을 찾습니다. forward를 수정하지 않고 활성을 캡처하는 것은 register_forward_hook입니다. 수용 영역은 깊이와 풀링으로 자라며, 대략 출력 픽셀 (i,j)가 그곳을 중심으로 한 크기 = 그 레이어까지의 stride와 커널의 합인 입력 패치에 의존합니다.

pytorch
# visualize feature maps
model.eval()
x = images[0:1].to(device)
with torch.no_grad():
    feat = model.features[0](x)   # first conv output
print(feat.shape)                 # (1, 32, H, W)

import matplotlib.pyplot as plt
fig, axes = plt.subplots(4, 8, figsize=(12, 6))
for i, ax in enumerate(axes.flat):
    if i < feat.shape[1]:
        ax.imshow(feat[0, i].cpu(), cmap='viridis')
    ax.axis('off')

# hook to capture intermediate activations
acts = {}
def hook(module, inp, out): acts['layer'] = out
model.features[3].register_forward_hook(hook)

Batch Normalization

BatchNorm2d가 (N, H, W)에 걸쳐 채널별 정규화하며 추론용 running EMA 통계를 유지합니다. train()/eval()이 중요합니다. eval은 running stats를 써 출력이 결정적입니다. BatchNorm이 배치 내 예시를 결합하므로 매우 작은 배치에서는 깨지고, 그때 GroupNorm이나 LayerNorm으로 전환하세요. 올바른 멀티 GPU BN에는 SyncBatchNorm이 필요합니다.

pytorch
import torch.nn as nn

# 2D BN for conv outputs
bn = nn.BatchNorm2d(64)
bn.weight.shape    # (64,) — learnable scale gamma
bn.bias.shape      # (64,) — learnable shift beta
bn.running_mean.shape  # (64,) — EMA of batch means
bn.running_var.shape   # (64,) — EMA of batch vars

# 1D BN for linear / time-series
bn1d = nn.BatchNorm1d(128)

# in training mode: use batch stats, update running stats
model.train()
# in eval mode: use running stats (deterministic)
model.eval()

# alternatives
nn.LayerNorm(128)        # normalize over features (transformers)
nn.GroupNorm(8, 64)      # split channels into 8 groups
nn.InstanceNorm2d(64)    # per-sample, style transfer

인기 CNN 아키텍처

torchvision.models가 사전학습 ImageNet 가중치와 함께 ResNet, EfficientNet, MobileNet, ViT 등을 노출합니다. 최종 fc 레이어 교체가 표준 전이 학습 진입점입니다. 검출/세그먼테이션에는 헤드를 떼고 conv 피처를 쓰세요. weights API(WeightsEnum)를 확인하세요. 오래된 pretrained=True 플래그는 폐기 예정입니다. 각 모델은 알려진 수용 영역과 FLOPs 예산이 있으니 지연 목표에 맞는 것을 고르세요.

pytorch
import torchvision.models as M

# pretrained backbones
resnet = M.resnet50(weights=M.ResNet50_Weights.DEFAULT)
effnet = M.efficientnet_b0(weights=M.EfficientNet_B0_Weights.DEFAULT)
vgg = M.vgg16(weights=M.VGG16_Weights.DEFAULT)
mobnet = M.mobilenet_v3_small(weights=M.MobileNet_V3_Small_Weights.DEFAULT)

# replace classifier head
num_classes = 100
resnet.fc = nn.Linear(resnet.fc.in_features, num_classes)

# feature extractor (drop head)
backbone = nn.Sequential(*list(resnet.children())[:-1])  # outputs (N, 2048, 1, 1)
features = backbone(images).flatten(1)                    # (N, 2048)
12

RNN과 LSTM

RNN 레이어

batch_first=True가 (batch, seq, feature) 입력을 만들어 대부분의 NLP 관례와 일치합니다. 없으면 PyTorch는 (seq, batch, feature)를 씁니다. 바닐라 RNN은 긴 시퀀스에서 그래디언트 소실에 시달리므로 실무에는 LSTM이나 GRU를 선호하세요. out이 마지막 레이어의 시점별 은닉 상태를, h_n이 각 레이어의 최종 상태를 담습니다.

pytorch
import torch.nn as nn

rnn = nn.RNN(
    input_size=64,
    hidden_size=128,
    num_layers=2,
    batch_first=True,        # input shape (batch, seq, feature)
    bidirectional=False,
    nonlinearity='tanh',
)

x = torch.randn(32, 10, 64)  # (batch, seq, input)
out, h_n = rnn(x)
print(out.shape)             # (32, 10, 128) — per-step hidden states
print(h_n.shape)             # (2, 32, 128) — final hidden state per layer

# last-step output for classification
last = out[:, -1, :]         # shape (32, 128)

LSTM 레이어

LSTM이 은닉 상태 h_n과 셀 상태 c_n을 모두 반환합니다. 양방향이 출력 피처 크기를 두 배로 합니다. 분류에는 각 방향의 최종 은닉 상태를 쓰세요(h_n[-2]가 마지막 forward 레이어, h_n[-1]이 마지막 backward 레이어). nn.LSTM의 dropout은 (입력이 아니라) 쌓인 레이어 사이에만 적용되므로 필요하면 입력을 nn.Dropout으로 감싸세요.

pytorch
import torch.nn as nn

lstm = nn.LSTM(
    input_size=64,
    hidden_size=128,
    num_layers=2,
    batch_first=True,
    bidirectional=True,
    dropout=0.5,             # between stacked layers
)

x = torch.randn(32, 10, 64)
out, (h_n, c_n) = lstm(x)
print(out.shape)    # (32, 10, 256) — 128 * 2 directions
print(h_n.shape)    # (4, 32, 128) — 2 layers * 2 directions
print(c_n.shape)    # (4, 32, 128) — cell state

# concatenate final forward + backward for classification
last = torch.cat([h_n[-2], h_n[-1]], dim=1)   # shape (32, 256)

GRU 레이어

GRU는 (셀 상태 없이) 은닉 상태만 있고 게이트도 셋 대신 둘이라 파라미터가 더 적고 LSTM보다 약간 빠르게 학습됩니다. 경험적으로 GRU와 LSTM이 대부분의 작업에서 비슷하며 작은 데이터셋에는 GRU가 좋은 기본입니다. LSTM처럼 dropout은 쌓인 레이어 사이에만 적용됩니다.

pytorch
import torch.nn as nn

gru = nn.GRU(
    input_size=64,
    hidden_size=128,
    num_layers=2,
    batch_first=True,
)

x = torch.randn(32, 10, 64)
out, h_n = gru(x)            # GRU has no cell state
print(out.shape)             # (32, 10, 128)
print(h_n.shape)             # (2, 32, 128)

# GRU vs LSTM: fewer parameters, slightly faster,
# often similar performance on many tasks

Packed 시퀀스

packing이 RNN 계산에서 패딩 토큰을 건너뛰어 더 빠르고 pad 0으로 은닉 상태가 편향되는 것을 피합니다. 오래된 PyTorch는 시퀀스가 길이 내림차순 정렬되어야 하며, enforce_sorted=False가 (약간의 오버헤드로) 내부에서 정렬합니다. 패딩 텐서로 되돌리는 것은 pad_packed_sequence이며 배치를 동적으로 패딩하는 커스텀 collate_fn과 결합하세요.

pytorch
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence

# variable-length sequences in a batch
seqs = [torch.randn(5, 64), torch.randn(3, 64), torch.randn(8, 64)]
lens = torch.tensor([5, 3, 8])

# pad to (batch, max_len, feature)
padded = torch.nn.utils.rnn.pad_sequence(seqs, batch_first=True)
# sort by length descending (required by older versions)
padded = padded[torch.argsort(lens, descending=True)]
lens_sorted = lens[torch.argsort(lens, descending=True)]

packed = pack_padded_sequence(padded, lens_sorted,
                              batch_first=True, enforce_sorted=True)
out_packed, h_n = lstm(packed)
out, _ = pad_packed_sequence(out_packed, batch_first=True)

시퀀스 분류

표준 텍스트 분류기: embedding -> biLSTM -> dropout -> linear. pad 토큰이 0 그래디언트를 갖게 nn.Embedding에 padding_idx를 쓰세요. (CPU에서 실행되는) pack_padded_sequence에는 lengths.cpu()를 전달하세요. 전체 시퀀스를 담으려 양방향의 최종 은닉 상태를 연결합니다. 긴 시퀀스에는 트랜스포머가 LSTM보다 낫지만 더 많은 데이터와 계산이 필요합니다.

pytorch
import torch.nn as nn

class TextClassifier(nn.Module):
    def __init__(self, vocab, emb_dim=128, hidden=256, classes=10):
        super().__init__()
        self.emb = nn.Embedding(vocab, emb_dim, padding_idx=0)
        self.lstm = nn.LSTM(emb_dim, hidden, batch_first=True,
                            bidirectional=True, num_layers=2)
        self.dropout = nn.Dropout(0.5)
        self.fc = nn.Linear(hidden * 2, classes)

    def forward(self, x, lengths):
        x = self.emb(x)
        packed = pack_padded_sequence(x, lengths.cpu(),
                                      batch_first=True, enforce_sorted=False)
        _, (h_n, _) = self.lstm(packed)
        last = torch.cat([h_n[-2], h_n[-1]], dim=1)
        return self.fc(self.dropout(last))

model = TextClassifier(vocab=10000)

시퀀스 생성 (디코더)

디코더는 이전 출력 토큰에 조건화되며 한 번에 한 스텝씩 실행됩니다. 단일 스텝 LSTM은 LSTMCell이며 루프의 세밀한 제어에 씁니다. teacher forcing이 학습 중 다음 스텝에 정답 토큰을 먹여 모델 자기 예측을 먹이는 것보다 훨씬 빨리 수렴하게 합니다. 추론에서는 이전 스텝의 로짓에서 argmax(또는 샘플)를 먹이는 것으로 전환하세요.

pytorch
import torch.nn as nn

class Decoder(nn.Module):
    def __init__(self, vocab, emb_dim=128, hidden=256):
        super().__init__()
        self.emb = nn.Embedding(vocab, emb_dim)
        self.lstm = nn.LSTMCell(emb_dim, hidden)
        self.fc = nn.Linear(hidden, vocab)

    def forward(self, tgt, hidden):
        # tgt shape (batch, T)
        outputs = []
        h, c = hidden
        for t in range(tgt.size(1)):
            emb = self.emb(tgt[:, t])
            h, c = self.lstm(emb, (h, c))
            outputs.append(self.fc(h))
        return torch.stack(outputs, dim=1)   # (batch, T, vocab)

# teacher forcing: feed ground truth next token
# at inference: feed argmax of previous output
13

트랜스포머

nn.MultiheadAttention

nn.MultiheadAttention이 헤드 병렬로 스케일된 점곱 어텐션을 계산합니다. NLP 관례(batch, seq, dim) 일치는 batch_first입니다. 인과적 디코딩(하삼각 마스크)은 attn_mask, 패딩 토큰 무시는 key_padding_mask입니다. need_weights=True가 (시각화와 탐침에 유용한) 어텐션 행렬을 반환합니다.

pytorch
import torch.nn as nn

attn = nn.MultiheadAttention(
    embed_dim=512,
    num_heads=8,
    dropout=0.1,
    batch_first=True,        # input (batch, seq, dim)
)

q = k = v = torch.randn(32, 10, 512)
out, weights = attn(q, k, v, need_weights=True)
print(out.shape)       # (32, 10, 512)
print(weights.shape)   # (32, 10, 10) — attention scores

# causal / self-attention mask
mask = nn.Transformer.generate_square_subsequent_mask(10)
out, _ = attn(q, k, v, attn_mask=mask)   # masked attention

# key padding mask (ignore pad positions)
key_padding_mask = (tokens == 0)   # True = ignore
out, _ = attn(q, k, v, key_padding_mask=key_padding_mask)

트랜스포머 인코더

TransformerEncoderLayer는 잔차와 LayerNorm이 있는 self-attention + FFN 블록입니다. 처음부터 학습에는 norm_first=True(pre-LN)가 더 안정하고, post-LN(기본)은 워밍업이 필요합니다. N개 레이어 스택은 nn.TransformerEncoder입니다. 어텐션이 pad 위치를 무시하도록 src_key_padding_mask를 전달하세요. 분류에는 출력 시퀀스를 평균 풀링해 Linear 헤드로 먹이세요.

pytorch
import torch.nn as nn

enc_layer = nn.TransformerEncoderLayer(
    d_model=512,
    nhead=8,
    dim_feedforward=2048,
    dropout=0.1,
    activation='relu',
    batch_first=True,
    norm_first=True,        # pre-LN, more stable
)
encoder = nn.TransformerEncoder(enc_layer, num_layers=6)

x = torch.randn(32, 10, 512)
out = encoder(x)
print(out.shape)            # (32, 10, 512)

# with padding mask
pad_mask = (tokens == 0)
out = encoder(x, src_key_padding_mask=pad_mask)

위치 인코딩

트랜스포머는 순열 불변이므로 위치 정보가 필요합니다. 사인파 인코딩이 학습에서 본 것보다 긴 시퀀스로 일반화됩니다. register_buffer가 pe를 파라미터로 만들지 않고 저장하며 .to(device)와 함께 움직이고 state_dict에 저장됩니다. (nn.Parameter의) 학습된 위치 임베딩도 동작하지만 학습 길이를 넘어 외삽하지 못합니다.

pytorch
import torch
import torch.nn as nn
import math

class PositionalEncoding(nn.Module):
    def __init__(self, d_model=512, max_len=5000, dropout=0.1):
        super().__init__()
        self.dropout = nn.Dropout(dropout)
        pe = torch.zeros(max_len, d_model)
        pos = torch.arange(0, max_len).unsqueeze(1).float()
        div = torch.exp(torch.arange(0, d_model, 2).float()
                        * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(pos * div)
        pe[:, 1::2] = torch.cos(pos * div)
        self.register_buffer('pe', pe.unsqueeze(0))   # (1, max_len, d_model)

    def forward(self, x):
        x = x + self.pe[:, :x.size(1)]
        return self.dropout(x)

# usage
emb = nn.Embedding(vocab, 512)
pos = PositionalEncoding(512)
x = pos(emb(tokens))   # (batch, seq, 512)

완전한 트랜스포머 (Seq2Seq)

번역/요약용 완전한 인코더-디코더 트랜스포머입니다. 디코더가 (위치 t가 <= t에만 주의하도록) 타깃에 인과적 마스킹을 쓰고 인코더 출력(memory)으로 교차 어텐션합니다. 어텐션이 pad 토큰을 무시하도록 소스와 타깃 둘 다 key_padding_mask를 전달하세요. 헤드가 디코더 출력을 어휘 로짓으로 투영하며, 손실은 ignore_index=0인 CrossEntropyLoss입니다.

pytorch
import torch.nn as nn

class Seq2SeqTransformer(nn.Module):
    def __init__(self, vocab_src, vocab_tgt, d=512, h=8, layers=6):
        super().__init__()
        self.src_emb = nn.Embedding(vocab_src, d, padding_idx=0)
        self.tgt_emb = nn.Embedding(vocab_tgt, d, padding_idx=0)
        self.pos = PositionalEncoding(d)
        enc_layer = nn.TransformerEncoderLayer(d, h, d*4, batch_first=True, norm_first=True)
        dec_layer = nn.TransformerDecoderLayer(d, h, d*4, batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(enc_layer, layers)
        self.decoder = nn.TransformerDecoder(dec_layer, layers)
        self.head = nn.Linear(d, vocab_tgt)

    def forward(self, src, tgt, src_pad, tgt_pad):
        src = self.pos(self.src_emb(src))
        tgt = self.pos(self.tgt_emb(tgt))
        memory = self.encoder(src, src_key_padding_mask=src_pad)
        causal = nn.Transformer.generate_square_subsequent_mask(tgt.size(1))
        out = self.decoder(tgt, memory,
                           tgt_mask=causal,
                           tgt_key_padding_mask=tgt_pad,
                           memory_key_padding_mask=src_pad)
        return self.head(out)

Vision Transformer (ViT) 블록

ViT 블록은 잔차가 있는 pre-LN 셀프 어텐션 + pre-LN MLP로 사실상 트랜스포머 인코더 레이어와 같습니다. Vision Transformer는 (kernel=stride=patch_size인) 스트라이드 Conv2d로 이미지를 패치화한 뒤 패치를 토큰으로 취급합니다. CLS 토큰과 위치 임베딩을 추가하세요. nn.MultiheadAttention이 (output, weights)를 반환하므로 weights를 건너뛰려 need_weights=False로 언팩하세요.

pytorch
import torch.nn as nn

class ViTBlock(nn.Module):
    def __init__(self, dim=768, heads=12, mlp=3072, dropout=0.1):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, heads, dropout=dropout, batch_first=True)
        self.norm2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(
            nn.Linear(dim, mlp),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(mlp, dim),
            nn.Dropout(dropout),
        )

    def forward(self, x):
        h = self.norm1(x)
        a, _ = self.attn(h, h, h, need_weights=False)
        x = x + a
        x = x + self.mlp(self.norm2(x))
        return x

# patchify: (B, 3, 224, 224) -> (B, 196, 768) via Conv2d(3, 768, 16, 16)

처음부터의 어텐션

스케일된 점곱 어텐션: scores = QK^T / sqrt(d_k), softmax, V 곱하기. 1/sqrt(d_k)가 분산을 안정시켜 softmax가 포화되지 않게 합니다. softmax 전 -inf로 masked_fill하면 해당 위치가 0이 됩니다. 멀티 헤드 어텐션이 임베딩을 H개 헤드로 나눠 병렬 어텐션 후 연결합니다. nn.MultiheadAttention이 정확히 이 일을 하므로 처음부터 쓰는 것은 학습이나 linear/flash attention 같은 변형 추가일 때만입니다.

pytorch
import torch
import torch.nn.functional as F
import math

def attention(q, k, v, mask=None, dropout=None):
    # q, k, v shape (batch, heads, seq, dim)
    d_k = q.size(-1)
    scores = (q @ k.transpose(-2, -1)) / math.sqrt(d_k)
    if mask is not None:
        scores = scores.masked_fill(mask == 0, float('-inf'))
    attn = F.softmax(scores, dim=-1)
    if dropout is not None:
        attn = dropout(attn)
    out = attn @ v
    return out, attn

# multi-head: reshape (batch, seq, dim) -> (batch, heads, seq, dim//heads)
def split_heads(x, heads):
    b, s, d = x.shape
    return x.view(b, s, heads, d // heads).transpose(1, 2)
14

GPU 학습

디바이스 선택

CPU 전용 머신이 크래시하지 않도록 항상 torch.cuda.is_available()로 게이트하세요. device= 인자로 텐서를 직접 디바이스에 만들 수 있으며(CPU 생성 후 이동보다 빠름) (PyTorch 2.x의) torch.device 컨텍스트가 새 텐서의 기본 디바이스를 정합니다. MPS가 Apple Silicon GPU를 지원하지만 일부 CUDA 기능이 없으니 의존 전 연산자 지원을 확인하세요.

pytorch
import torch

# pick device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)                          # cuda or cpu
print(torch.cuda.device_count())       # number of GPUs
print(torch.cuda.get_device_name(0))   # GPU name

# use a specific GPU
torch.cuda.set_device(0)
x = torch.randn(3, device='cuda:1')    # directly on GPU 1

# default device context (PyTorch 2.x)
with torch.device('cuda'):
    y = torch.randn(4)   # on GPU

# Apple Silicon
device = 'mps' if torch.backends.mps.is_available() else 'cpu'

모델과 데이터 이동

model.to(device)가 파라미터와 버퍼를 제자리에서 옮깁니다. DataLoader가 디스크에서 스트리밍할 수 있도록 입력 텐서는 학습 루프 안에서 옮기세요. 소스 텐서가 고정 메모리에 있으면(DataLoader에 pin_memory=True) non_blocking=True가 CPU→GPU 복사를 계산과 겹칩니다. NumPy 연산 전에는 .cpu() / .numpy()를 하세요. GPU 텐서는 직접 변환할 수 없습니다.

pytorch
model = MLP(784, 128, 10).to(device)

for x, y in train_loader:
    x, y = x.to(device), y.to(device)
    # non-blocking copy if pin_memory=True
    x = x.to(device, non_blocking=True)
    ...

# check placement
print(next(model.parameters()).device)   # cuda:0
print(x.device)

# move a tensor to CPU for numpy / saving
arr = x.detach().cpu().numpy()

# half precision
model = model.half()        # float16
x = x.half()

다중 GPU (DataParallel)

DataParallel(DP)이 각 GPU에 모델을 복제하고 배치를 나눠 출력을 GPU 0에 모읍니다. 쉽지만 느리고 불균형합니다(GPU 0이 gather와 손실 계산을 함). 단일 프로세스이므로 GIL이 확장을 제한합니다. 진지한 멀티 GPU 작업에는 대신 DistributedDataParallel을 쓰세요. DP는 2~4 GPU의 빠른 프로토타이핑에는 괜찮습니다.

pytorch
import torch.nn as nn

# simple, single-process data parallelism
model = MLP(784, 512, 10).to(device)
model = nn.DataParallel(model)   # wrap AFTER .to(device)

# now model behaves normally
out = model(x)
loss = criterion(out, y)
loss.backward()   # gradients are summed across GPUs

# access underlying module
inner = model.module

# specify which GPUs
model = nn.DataParallel(model, device_ids=[0, 1, 2])

DistributedDataParallel

DistributedDataParallel(DDP)이 GPU마다 프로세스를 하나 생성하며 각자 모델 복제본을 갖고, 그래디언트가 all-reduce되어 모든 GPU가 같은 그래디언트를 봅니다. DataParallel보다 훨씬 빠르고 확장성이 좋습니다. 프로세스 시작은 torchrun(또는 torch.distributed.launch)입니다. 각 에포크가 재셔플하도록 항상 sampler.set_epoch(epoch)을 호출하세요. 더 보려 분산 학습 섹션을 보세요.

pytorch
import os
import torch.distributed as dist
import torch.nn as nn

# launch with: torchrun --nproc_per_node=4 train.py
dist.init_process_group(backend='nccl')
local_rank = int(os.environ['LOCAL_RANK'])
torch.cuda.set_device(local_rank)

model = MLP(784, 512, 10).to(local_rank)
model = nn.parallel.DistributedDataParallel(
    model, device_ids=[local_rank], output_device=local_rank,
)

sampler = torch.utils.data.distributed.DistributedSampler(dataset)
loader = DataLoader(dataset, batch_size=64, sampler=sampler)

for epoch in range(epochs):
    sampler.set_epoch(epoch)   # shuffle differently each epoch
    for x, y in loader:
        x, y = x.to(local_rank), y.to(local_rank)
        loss = criterion(model(x), y)
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

메모리 관리

empty_cache()가 캐시된 메모리를 OS에 돌려주지만 사용 중인 텐서는 해제하지 않으므로 핫 루프가 아니라 큰 스파이크 뒤에 호출하세요. 사용 중 텐서는 memory_allocated이고 캐싱 할당자의 풀은 memory_reserved입니다. OOM 감소 방법: 배치 크기 축소, 혼합 정밀도, 그래디언트 체크포인팅, 그래디언트 누적. 가변 형상 워크로드의 단편화 감소는 expandable_segments:True입니다. 더 이상 필요 없는 텐서(예: 리스트에 쌓인 로그 손실)의 참조 유지는 피하세요.

pytorch
import torch

# release unused memory
torch.cuda.empty_cache()

# current memory usage
print(torch.cuda.memory_allocated() / 1e9, 'GB allocated')
print(torch.cuda.memory_reserved() / 1e9, 'GB reserved')

# per-tensor memory
x = torch.randn(1000, 1000, device='cuda')
print(x.element_size() * x.nelement() / 1e6, 'MB')

# peak memory tracking
torch.cuda.reset_peak_memory_stats()
# ... run training ...
print(torch.cuda.max_memory_allocated() / 1e9, 'GB peak')

# out-of-memory debugging
import os
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'

CuDNN과 성능

cudnn.benchmark=True가 cuDNN이 첫 forward에서 알고리즘을 프로파일하고 가장 빠른 것을 캐시하게 합니다. 입력 형상이 고정된(전형 CNN) 경우 좋고, 형상이 매 스텝 바뀌면(가변 길이 RNN) 해롭습니다. TF32는 Ampere+에서 19비트 가수로 최소 정확도 손실의 약 3배 matmul 가속을 주며 엄격한 fp32 재현이 필요하지 않으면 켜세요. 결정적 모드가 비결정적 알고리즘을 끕니다.

pytorch
import torch.backends.cudnn as cudnn

# benchmark finds the fastest conv algorithm (good for fixed input sizes)
cudnn.benchmark = True

# deterministic mode (slower, reproducible)
cudnn.deterministic = True
cudnn.benchmark = False

# allow TF32 on Ampere+ (big speedup, slight precision loss)
torch.backends.cuda.matmul.allow_tf32 = True
cudnn.allow_tf32 = True

# disable cudnn (debugging)
cudnn.enabled = False
15

Transforms와 전처리

흔한 Transforms

ToTensor가 PIL 이미지(0-255)를 [0,1] float 텐서로 바꾸고 HWC -> CHW로 재배열합니다. Normalize가 (사전학습 모델의 사실상 표준인) ImageNet 통계로 채널별 표준화하며 백본이 학습된 통계와 항상 일치시키세요. 워커 프로세스에서 실행되도록 transforms는 Dataset에 적용하세요. GPU가 CPU 전처리를 기다리지 않습니다.

pytorch
from torchvision import transforms

transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),                       # PIL -> Tensor, scales to [0,1]
    transforms.Normalize(                        # per-channel standardize
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225],
    ),
])

# apply to a PIL image
img = transform(pil_image)
print(img.shape)       # (3, 224, 224)
print(img.min(), img.max())   # standardized

dataset = datasets.ImageFolder('data/', transform=transform)

데이터 증강

증강이 다양한 입력을 보여줘 모델을 정규화합니다. RandomResizedCrop + flip이 고전 ImageNet 증강입니다. 기하에 영향 없이 색을 바꾸는 것은 ColorJitter이며, TrivialAugmentWide와 RandAugment가 무작위 크기의 무작위 연산을 샘플링합니다. 강하고 단순하며 의외로 효과적입니다. 지표가 안정되도록 검증에는 증강 없는 별도 transform을 쓰세요.

pytorch
from torchvision import transforms

train_tf = transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(brightness=0.2, contrast=0.2,
                           saturation=0.2, hue=0.1),
    transforms.RandomRotation(15),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

# stronger augmentation: RandAugment / TrivialAugment
train_tf = transforms.Compose([
    transforms.TrivialAugmentWide(),
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

Transforms v2 (새 API)

Transforms v2(torchvision 0.17+)가 새 API입니다. 더 빠르고 JIT-scriptable하며 결정적으로 image/mask/bbox에 함께 동작해 검출과 세그먼테이션 증강이 일관되게 유지됩니다. ToTensor 대체는 ToDtype + scale=True입니다. 더 깨끗한 다운샘플을 위해 resize 연산에는 항상 antialias=True를 전달하세요. 레거시 transforms 모듈은 동작하지만 새 기능은 안 받습니다.

pytorch
from torchvision.transforms import v2

transform = v2.Compose([
    v2.RandomResizedCrop(224, antialias=True),
    v2.RandomHorizontalFlip(),
    v2.ToDtype(torch.float32, scale=True),   # scale to [0,1]
    v2.Normalize(mean=[0.485, 0.456, 0.406],
                 std=[0.229, 0.224, 0.225]),
])

# v2 works on images, videos, masks, and bounding boxes together
imgs, masks = transform(imgs, masks)
imgs, bboxes, labels = transform(imgs, bboxes, labels)

# supports more ops and JIT scripting
transform = v2.RandomChoice([
    v2.RandomHorizontalFlip(),
    v2.RandomVerticalFlip(),
])

커스텀 Transform

커스텀 transform은 텐서(또는 PIL 이미지)를 받아 하나를 반환하는 임의 호출 가능 객체입니다. 결합은 transforms.Compose입니다. float에 대해 동작하도록 ToTensor 뒤에 노이즈를 적용하세요. 샘플별 무작위는 __call__ 안의 torch.rand로 호출마다 새 결정을 받습니다. Transforms v2는 forward를 재정의해 (이미지, 레이블) 결합 입력을 처리하는 transform 클래스를 쓰게 합니다.

pytorch
import torch
from torchvision import transforms

class RandomGaussianNoise:
    def __init__(self, std=0.1):
        self.std = std
    def __call__(self, x):
        if self.std > 0:
            return x + torch.randn_like(x) * self.std
        return x

# compose with built-ins
transform = transforms.Compose([
    transforms.ToTensor(),
    RandomGaussianNoise(0.05),
    transforms.Normalize([0.5], [0.5]),
])

# callable with probability
class RandomApply:
    def __init__(self, fn, p=0.5):
        self.fn, self.p = fn, p
    def __call__(self, x):
        return self.fn(x) if torch.rand(1) < self.p else x

텍스트와 테이블 전처리

텍스트에서는 (val/test가 아니라) 학습 셋에서 어휘를 만들고 토큰을 정수 id로 변환하세요. 보지 못한 단어는 <unk>가 처리하고 가변 길이 시퀀스 배칭에는 <pad>가 쓰입니다. 테이블 데이터는 학습 셋 '전용' 통계로 피처를 표준화하세요. val/test 통계 유출이 지표를 부풀립니다. 추론이 동일하게 전처리하도록 스케일러/어휘를 모델 체크포인트와 함께 저장하세요.

pytorch
import torch
from torchtext.vocab import build_vocab_from_iterator

# tokenize and numericalize text
tokens = ['hello', 'world', 'this', 'is', 'nlp']
vocab = build_vocab_from_iterator([tokens], specials=['<unk>', '<pad>'])
vocab.set_default_index(vocab['<unk>'])

# text -> token ids
ids = vocab(['hello', 'world', 'unknownword'])
print(ids)   # e.g. [3, 4, 0]

# tabular: standardize features
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(X_train)
X_train_t = torch.tensor(scaler.transform(X_train), dtype=torch.float32)
X_test_t = torch.tensor(scaler.transform(X_test), dtype=torch.float32)

# fit scaler ONLY on training data, apply to val/test
16

커스텀 Dataset

Dataset 클래스

Dataset에는 __len__과 __getitem__만 있으면 됩니다. 파일은 __getitem__ 안에서 느리게 열어 수백만 경로를 메모리에 싸게 들 수 있습니다. (input, target) 튜플을 반환하면 DataLoader의 기본 collate가 배치로 쌓습니다. 워커 프로세스에서 실행되므로 __getitem__은 저렴하고 부작용 없이 유지하고 공유 상태를 수정하지 마세요.

pytorch
from torch.utils.data import Dataset

class ImageDataset(Dataset):
    def __init__(self, paths, labels, transform=None):
        self.paths = paths
        self.labels = labels
        self.transform = transform

    def __len__(self):
        return len(self.paths)

    def __getitem__(self, idx):
        from PIL import Image
        img = Image.open(self.paths[idx]).convert('RGB')
        label = self.labels[idx]
        if self.transform:
            img = self.transform(img)
        return img, label

dataset = ImageDataset(paths, labels, transform=train_tf)
img, label = dataset[0]

Image Folder Dataset

ImageFolder는 클래스당 하나의 하위 디렉터리를 기대하고 폴더 이름으로 레이블을 추론합니다. 이미지 분류 시작의 가장 빠른 방법입니다. class_to_idx가 이름을 정수 레이블로 매핑하며 train/val/test에서 같은 매핑을 재사용해 일관되게 유지하세요. random_split은 기저 데이터를 공유하는 Subset을 반환하므로 메모리가 복제되지 않습니다.

pytorch
from torchvision import datasets

# convention: data/train/cat/*.jpg, data/train/dog/*.jpg
dataset = datasets.ImageFolder('data/train', transform=train_tf)
print(dataset.class_to_idx)   # {'cat': 0, 'dog': 1}

# train / val split
from torch.utils.data import random_split
train, val = random_split(dataset, [0.8, 0.2])

# custom split with same class mapping
val_dataset = datasets.ImageFolder('data/val', transform=val_tf)
val_dataset.class_to_idx = dataset.class_to_idx   # keep consistent

# use with DataLoader
loader = DataLoader(dataset, batch_size=32, shuffle=True, num_workers=4)

텍스트 Dataset

매 에포크 재토큰화를 피하려 텍스트를 한 번 미리 토큰화해 정수 id로 저장하세요. 가변 길이 시퀀스는 원시 리스트를 반환하고 collate_fn에서 패딩해 각 배치가 자기 최대 길이로만 패딩하게 하세요. RNN이 pad 위치를 건너뛰게 하는 것은 pack_padded_sequence입니다. 트랜스포머 학습에는 어텐션이 패딩 토큰을 무시하도록 어텐션 마스크를 반환하세요.

pytorch
from torch.utils.data import Dataset
import torch

class TextDataset(Dataset):
    def __init__(self, texts, labels, vocab, max_len=128):
        self.texts = texts
        self.labels = labels
        self.vocab = vocab
        self.max_len = max_len

    def __len__(self):
        return len(self.texts)

    def __getitem__(self, idx):
        tokens = self.texts[idx].split()[:self.max_len]
        ids = [self.vocab[t] for t in tokens]
        ids += [0] * (self.max_len - len(ids))   # pad
        return torch.tensor(ids), self.labels[idx]

# variable length: use custom collate
def text_collate(batch):
    ids, labels = zip(*batch)
    lens = torch.tensor([len(x) for x in ids])
    padded = torch.nn.utils.rnn.pad_sequence(ids, batch_first=True)
    return padded, lens, torch.tensor(labels)

Iterable Dataset

IterableDataset이 랜덤 접근 대신 스트리밍하며 (로그, 데이터베이스, S3 같은) 거대 또는 스트리밍 소스에 필수입니다. 모든 워커가 같은 데이터를 읽지 않게 워커는 스트림을 (itertools.islice로) 명시 분할해야 합니다. shuffle은 직접 지원되지 않으므로 샘플을 버퍼에 담아 버퍼 안에서 셔플하세요. 길이로 인덱싱할 수 없을 만큼 큰 데이터셋에 쓰세요.

pytorch
from torch.utils.data import IterableDataset, DataLoader
import itertools

class StreamDataset(IterableDataset):
    def __init__(self, file_path):
        self.file_path = file_path

    def __iter__(self):
        # split work across workers
        worker_info = torch.utils.data.get_worker_info()
        with open(self.file_path) as f:
            if worker_info is None:
                lines = f
            else:
                lines = itertools.islice(f, worker_info.id,
                                         None, worker_info.num_workers)
            for line in lines:
                yield self._parse(line)

    def _parse(self, line):
        # parse line into tensor + label
        return torch.tensor([...]), label

loader = DataLoader(StreamDataset('big.csv'), batch_size=32)

TensorDataset과 ConcatDataset

데이터가 RAM에 들어가면 TensorDataset이 가장 빠른 경로이며 기본 collate가 배치로 쌓는 텐서의 튜플을 반환합니다. ConcatDataset이 데이터셋을 끝에서 끝으로 사슬로 잇고 레이블 데이터와 의사 레이블 데이터 결합에 유용합니다. Subset이 데이터셋을 인덱스 목록으로 감싸 데이터 복사 없이 random_split과 커스텀 슬라이싱을 가능하게 합니다.

pytorch
from torch.utils.data import TensorDataset, ConcatDataset, DataLoader

# wrap in-memory tensors
X = torch.randn(1000, 784)
y = torch.randint(0, 10, (1000,))
dataset = TensorDataset(X, y)
x, label = dataset[0]

# combine multiple datasets
full = ConcatDataset([dataset_a, dataset_b])
print(len(full))   # len(a) + len(b)

# Subset for indexing
from torch.utils.data import Subset
half = Subset(dataset, range(500))

# random splits
from torch.utils.data import random_split
train, val = random_split(dataset, [0.8, 0.2])
17

LR 스케줄러

StepLR과 MultiStepLR

StepLR과 MultiStepLR이 가장 단순한 스케줄러로 고정 에포크에서 LR을 gamma로 곱합니다. 예측 가능하며 처음부터 학습하는 CNN에 잘 동작합니다. 스케줄러.step()은 배치 루프 안이 아니라 항상 에포크 학습 후에 호출하세요. 로깅용 현재 LR 확인은 get_last_lr()입니다. 주의: step_size는 스텝이 아니라 에포크를 셉니다.

pytorch
from torch.optim.lr_scheduler import StepLR, MultiStepLR

# decay by gamma every step_size epochs
scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
# LR: 1e-3 -> 1e-4 (epoch 10) -> 1e-5 (epoch 20)

# decay at specific epochs
scheduler = MultiStepLR(optimizer, milestones=[30, 60, 80], gamma=0.1)

# in the training loop
for epoch in range(epochs):
    train(...)
    val(...)
    scheduler.step()    # call once per epoch

# inspect current LR
print(scheduler.get_last_lr())

CosineAnnealingLR

코사인 어닐링이 LR을 부드럽게 감쇠하며 step 감쇠보다 작은 정확도 상승을 내는 경우가 많습니다. 워밍 재시작(SGDR)이 각 사이클 시작에서 LR을 기저 값으로 리셋해 모델이 날카로운 최소값을 벗어나게 돕고, T_mult=2가 각 사이클을 두 배로 길게 합니다. 코사인 스케줄러가 이미지 분류와 사전학습의 현대 기본입니다.

pytorch
from torch.optim.lr_scheduler import CosineAnnealingLR

# cosine decay to eta_min over T_max epochs
scheduler = CosineAnnealingLR(optimizer, T_max=50, eta_min=1e-6)
# LR follows cosine from base_lr down to eta_min

# with warm restarts
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
scheduler = CosineAnnealingWarmRestarts(
    optimizer,
    T_0=10,             # length of first cycle
    T_mult=2,           # each cycle is T_mult longer
    eta_min=1e-6,
)

ReduceLROnPlateau

ReduceLROnPlateau가 지표를 지켜 개선이 멈추면 LR을 줄입니다. 올바른 스케줄을 미리 모를 때 완벽합니다. 손실은 mode='min', 정확도는 'max'입니다. patience=N이 감소 전 N 에포크의 무개선을 기다립니다. 다른 스케줄러와 달리 step(metric)에 지표를 반드시 전달해야 합니다. patience가 너무 크면 과적합하기 쉬우니 조기 중단과 결합하세요.

pytorch
from torch.optim.lr_scheduler import ReduceLROnPlateau

scheduler = ReduceLROnPlateau(
    optimizer,
    mode='min',         # 'min' for loss, 'max' for accuracy
    factor=0.5,         # multiply LR by factor on plateau
    patience=3,         # epochs to wait before reducing
    min_lr=1e-7,
    threshold=1e-4,
)

for epoch in range(epochs):
    train(...)
    val_loss = validate(...)
    scheduler.step(val_loss)   # pass the metric!

OneCycleLR과 CyclicLR

OneCycleLR(초수렴)이 워밍업, 정점, 어닐링으로 주어진 정확도에 모델을 가장 빨리 학습시키는 경우가 많습니다. 배치별로 step하므로 total_steps = epochs * batches_per_epoch를 설정하세요. pct_start=0.3가 스텝의 30%를 워밍업에 씁니다. 기저와 최대 LR 사이를 진동하는 CyclicLR은 (LR range test처럼) 좋은 LR 찾기에 유용합니다.

pytorch
from torch.optim.lr_scheduler import OneCycleLR

# one cycle: warm up, peak, anneal down
scheduler = OneCycleLR(
    optimizer,
    max_lr=1e-3,
    total_steps=epochs * len(loader),   # or steps_per_epoch + epochs
    pct_start=0.3,       # fraction spent warming up
    anneal_strategy='cos',
)

# step per BATCH (not per epoch)
for epoch in range(epochs):
    for x, y in loader:
        train_step(...)
        scheduler.step()   # call once per batch

# simpler cyclic LR
from torch.optim.lr_scheduler import CyclicLR
scheduler = CyclicLR(optimizer, base_lr=1e-5, max_lr=1e-3, step_size_up=500)

Warmup + Decay

Warmup이 Adam의 2차 모멘트 추정이 나쁜 조건일 때 첫 스텝을 안정시키며 트랜스포머 학습에 필수입니다. 워밍업과 임의 감쇠 스케줄의 깔끔 결합은 LinearLR + SequentialLR입니다. (스텝 수의 함수로) 완전한 제어는 LambdaLR이며 가장 유연한 스케줄러입니다. HuggingFace식 스케줄은 transformers.get_cosine_schedule_with_warmup을 보세요.

pytorch
from torch.optim.lr_scheduler import LinearLR, SequentialLR, CosineAnnealingLR

# linear warmup for first N steps
warmup = LinearLR(optimizer, start_factor=0.1, total_iters=500)

# cosine decay after warmup
cosine = CosineAnnealingLR(optimizer, T_max=total_steps - 500, eta_min=1e-6)

# combine
scheduler = SequentialLR(
    optimizer,
    schedulers=[warmup, cosine],
    milestones=[500],
)

# manual warmup (transformers-style)
def lr_lambda(step):
    if step < 500:
        return step / 500
    return 0.5 * (1 + math.cos(math.pi * (step - 500) / (total - 500)))

from torch.optim.lr_scheduler import LambdaLR
scheduler = LambdaLR(optimizer, lr_lambda)

커스텀 스케줄러

LambdaLR이 기저 LR을 lambda(step)로 곱해 커스텀 스케줄 구현의 가장 유연한 방법입니다. 그룹별 스케줄(예: 편향이 아니라 가중치 감쇠, 전이 학습에서 백본과 헤드의 다른 스케줄)에는 (param_group마다 하나의) lambda 목록을 전달하세요. lambda는 매 스텝 실행되므로 저렴해야 하며 가변 상태를 캡처하는 Python 클로저는 피하고 순수하게 유지하세요.

pytorch
from torch.optim.lr_scheduler import LambdaLR
import math

# any function of step / epoch
def warmup_cosine(step, warmup=500, total=10000):
    if step < warmup:
        return step / warmup
    progress = (step - warmup) / (total - warmup)
    return 0.5 * (1 + math.cos(math.pi * progress))

scheduler = LambdaLR(optimizer, lr_lambda=warmup_cosine)

# per-parameter-group schedule (e.g. decay only weights, not bias)
scheduler = LambdaLR(
    optimizer,
    lr_lambda=[lambda s: 0.9 ** s, lambda s: 1.0],  # one per group
)

# inspect
for step in range(0, total, 1000):
    print(step, scheduler.get_last_lr())
    scheduler.step()
18

전이 학습

사전학습 모델

WeightsEnum API를 항상 쓰세요(DEFAULT가 최선 사용 가능 선택). 오래된 pretrained=True는 폐기 예정입니다. 각 weights 객체가 모델이 학습된 정확한 전처리를 반환하는 .transforms()를 노출하므로 입력이 일치하게 이것을 쓰세요. 분류 헤드가 ImageNet의 1000 클래스를 출력하므로 자기 작업용으로 교체하세요.

pytorch
import torchvision.models as M

# load a model with pretrained ImageNet weights
weights = M.ResNet50_Weights.DEFAULT
model = M.resnet50(weights=weights)

# get the matching preprocessing transform
preprocess = weights.transforms()
print(preprocess)   # resize, crop, normalize with ImageNet stats

# model is ready for 1000-class ImageNet inference
model.eval()
with torch.no_grad():
    out = model(preprocess(img).unsqueeze(0))
    pred = out.argmax(1)
    print(weights.meta['categories'][pred])

피처 추출

피처 추출이 백본을 고정하고 새 헤드만 학습합니다. 가장 빠른 전이 학습 기저선으로 작은 데이터셋의 몇 분 학습으로 높은 정확도에 도달하는 경우가 많습니다. 백본이 고정되어 피처를 한 번 미리 계산하고 싼 분류기를 그 위에 학습시켜 막대한 계산을 아낄 수 있습니다. 헤드 학습 중에도 BatchNorm이 running stats를 쓰도록 model.eval()을 설정하세요.

pytorch
import torch.nn as nn
import torchvision.models as M

# load backbone, freeze it, replace head
model = M.resnet50(weights=M.ResNet50_Weights.DEFAULT)

# freeze all parameters
for p in model.parameters():
    p.requires_grad_(False)

# replace classifier for new task (10 classes)
model.fc = nn.Linear(model.fc.in_features, 10)
# only the new fc has requires_grad=True

# train only the head
optimizer = torch.optim.Adam(model.fc.parameters(), lr=1e-3)

# inference-friendly: extract features once
features = torch.nn.Sequential(*list(model.children())[:-1])
feat = features(images).flatten(1)   # (N, 2048)

파인튜닝

파인튜닝이 (모델 전체 또는 일부를) 작은 LR로 학습해 사전학습 피처가 자기 작업에 적응하게 합니다. 차등 LR을 쓰세요. 초기 레이어(일반 피처)는 작게, 헤드(작업별)는 크게. 점진적 해제(헤드를 먼저 학습한 뒤 더 깊은 레이어 해제)가 한 번에 전부 학습하는 것보다 더 안정하며 작은 데이터셋에서 특히 그렇습니다.

pytorch
import torch.nn as nn
import torch.optim as optim
import torchvision.models as M

model = M.resnet50(weights=M.ResNet50_Weights.DEFAULT)
model.fc = nn.Linear(model.fc.in_features, 10)

# differential learning rates: lower for backbone, higher for head
optimizer = optim.Adam([
    {'params': [p for n, p in model.named_parameters() if 'fc' not in n], 'lr': 1e-4},
    {'params': model.fc.parameters(), 'lr': 1e-3},
])

# gradual unfreezing: train head first, then unfreeze later layers
def unfreeze(layer_idx):
    for n, p in model.named_parameters():
        if f'layer{layer_idx}' in n:
            p.requires_grad_(True)

# warmup head only for a few epochs, then unfreeze layer4, etc.

레이어 고정과 해제

requires_grad_(False)가 autograd가 파라미터를 추적·갱신하는 것을 멈추지만, 그래디언트는 여전히 고정 레이어를 지나 다운스트림 학습 가능 레이어로 흐릅니다. 선택적 고정은 named_parameters()로 레이어 이름 기준 필터입니다. 실수로 전부 고정하는(흔한 조용한 버그) 일이 없도록 학습 가능 파라미터 수를 항상 로그하세요. 해제 뒤에는 새로 학습 가능한 파라미터를 잡도록 옵티마이저를 재생성하세요.

pytorch
model = M.resnet50(weights=M.ResNet50_Weights.DEFAULT)
model.fc = nn.Linear(model.fc.in_features, 10)

# freeze everything except fc
for name, p in model.named_parameters():
    p.requires_grad = ('fc' in name)

# freeze specific submodule
for p in model.layer1.parameters():
    p.requires_grad_(False)

# count trainable params
n = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"trainable: {n:,}")

# unfreeze after warmup
for p in model.layer4.parameters():
    p.requires_grad_(True)

# trainable params still need grad to flow: ensure no torch.no_grad
# and that frozen layers don't break autograd

분류기 교체

아키텍처마다 분류기 속성이 다릅니다. ResNet은 .fc, EfficientNet은 .classifier[1], ViT는 .heads.head. 새 헤드를 requires_grad=True로 설정하면 초기에 그것만 학습됩니다. 멀티태스크 학습에서는 백본을 공유하는 여러 Linear 레이어로 헤드를 교체하세요. (no-op 모듈인) nn.Identity()가 원래 헤드를 깔끔히 빼는 데 편리합니다.

pytorch
import torch.nn as nn
import torchvision.models as M

model = M.resnet50(weights=M.ResNet50_Weights.DEFAULT)
# ResNet: model.fc
model.fc = nn.Linear(model.fc.in_features, num_classes)

# EfficientNet: model.classifier[1]
model = M.efficientnet_b0(weights=M.EfficientNet_B0_Weights.DEFAULT)
model.classifier[1] = nn.Linear(model.classifier[1].in_features, num_classes)

# ViT: model.heads.head
model = M.vit_b_16(weights=M.ViT_B_16_Weights.DEFAULT)
model.heads.head = nn.Linear(model.heads.head.in_features, num_classes)

# multi-task head
class MultiTask(nn.Module):
    def __init__(self, backbone, n_cls, n_reg):
        super().__init__()
        self.backbone = backbone
        in_f = backbone.fc.in_features
        backbone.fc = nn.Identity()
        self.cls = nn.Linear(in_f, n_cls)
        self.reg = nn.Linear(in_f, n_reg)
    def forward(self, x):
        f = self.backbone(x)
        return self.cls(f), self.reg(f)
19

시각화

TensorBoard 설정

SummaryWriter가 이벤트를 로그 디렉터리로 스트리밍하며 보기는 `tensorboard --logdir=runs`로 실행합니다. 단일 지표 대 스텝 플롯은 add_scalar이고 한 차트에 여러 곡선 겹치기는 add_scalars입니다. 같은 UI에서 실행 비교를 위해 실험별로 별도 하위 디렉터리(runs/exp1, runs/exp2)를 쓰세요. 마지막 이벤트가 쓰이도록 끝에 writer.close()로 플러시하세요.

pytorch
from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter('runs/experiment_1')

# log scalars (loss, accuracy, LR)
writer.add_scalar('train/loss', loss.item(), step)
writer.add_scalar('val/accuracy', acc, step)
writer.add_scalar('lr', optimizer.param_groups[0]['lr'], step)

# log multiple metrics together
writer.add_scalars('losses', {
    'train': train_loss,
    'val': val_loss,
}, step)

# close at the end
writer.close()

# launch: tensorboard --logdir=runs

그래프와 히스토그램 로깅

add_graph가 Graphs 탭에서 모델 아키텍처를 시각화하며 forward 흐름 디버깅에 유용합니다. 시간에 걸친 가중치나 그래디언트 분포는 add_histogram이며, 건강한 학습은 그래디언트가 nonzero이고 가중치가 대략 종 모양입니다. grad 히스토그램의 급스파이크는 불안정을 암시합니다. 매 스텝 로깅은 느리므로 N 스텝마다 샘플하세요.

pytorch
writer = SummaryWriter('runs/exp')

# log model graph (needs a sample input)
model = MLP(784, 128, 10)
writer.add_graph(model, torch.randn(1, 784))

# weight histograms (per layer, over training)
for name, p in model.named_parameters():
    writer.add_histogram(f'weights/{name}', p, step)
    if p.grad is not None:
        writer.add_histogram(f'grads/{name}', p.grad, step)

# text
writer.add_text('config', 'lr=1e-3, batch=32', 0)

# close at the end
writer.close()

이미지 로깅

add_image가 CHW 텐서를 받으며, 배치를 표시 가능 범위로 스케일해 하나의 이미지로 타일링하는 것은 normalize=True를 준 make_grid입니다. matplotlib Figure 직접 로그는 add_figure입니다. 빠른 시각 QA를 위한 예측 오버레이는 (torchvision.utils의) draw_segmentation_masks와 draw_bboxes입니다. 스칼라 지표만이 아니라 정성적 진행을 모니터링하려 에포크마다 검증 샘플 몇 개를 로그하세요.

pytorch
writer = SummaryWriter('runs/exp')

# single image (CHW tensor in [0,1] or [0,255])
writer.add_image('val/sample', img_tensor, step)

# grid of images
from torchvision.utils import make_grid
grid = make_grid(images, nrow=8, normalize=True)
writer.add_image('val/batch', grid, step)

# figure from matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3], [1,4,9])
writer.add_figure('curves/loss', fig, step)

# overlay segmentation mask on image
from torchvision.utils import draw_segmentation_masks
overlay = draw_segmentation_masks(img, masks, alpha=0.5)
writer.add_image('val/masks', overlay, step)

torchviz 그래프

torchviz가 단일 forward 패스의 autograd 그래프를 그려 형상 불일치, 의도치 않은 분기, detach된 텐서 디버깅에 좋습니다. 각 노드가 연산이고 엣지가 텐서 흐름을 보여 줍니다. (backward를 위해 유지된) 중간 텐서 표시는 show_saved=True이며 메모리 사용량을 결정하는 것이 이것입니다. 설치는 `pip install torchviz`와 시스템 PATH의 Graphviz입니다.

pytorch
from torchviz import make_dot

x = torch.randn(1, 784, requires_grad=True)
y = model(x)
loss = criterion(y, torch.tensor([1]))
loss.backward()

# render the autograd graph
dot = make_dot(loss, params=dict(model.named_parameters()))
dot.render('model_graph', format='png')   # saves model_graph.png

# also show saved tensors (memory)
dot = make_dot(loss, params=dict(model.named_parameters()),
               show_attrs=True, show_saved=True)

가중치와 활성 탐침

첫 레이어 필터 시각화가 모델이 '무엇을 찾는지'(엣지, 색, 텍스처) 보여 줍니다. forward를 수정하지 않고 활성을 캡처하는 forward 훅이 중간 레이어 탐침이나 피처 추출기 구축에 완벽합니다. 죽은 뉴런(0 그래디언트)이나 폭주 활성을 잡으려 스텝별 가중치와 그래디언트 통계(mean, std, norm)를 추적하세요. 깔끔한 레이어별 파라미터 표는 torchsummary나 torchinfo입니다.

pytorch
import matplotlib.pyplot as plt

# visualize conv filters
filters = model.features[0].weight.data.clone().cpu()
fig, axes = plt.subplots(4, 8, figsize=(10, 5))
for i, ax in enumerate(axes.flat):
    if i < filters.size(0):
        ax.imshow(filters[i, 0], cmap='gray')
    ax.axis('off')

# hook to capture activations
acts = {}
def hook(name):
    def fn(mod, inp, out): acts[name] = out.detach().cpu()
    return fn
model.features[3].register_forward_hook(hook('l1'))

# activation statistics over training
for name, p in model.named_parameters():
    print(name, p.data.mean().item(), p.data.std().item(),
          p.grad.norm().item() if p.grad is not None else None)
20

분산 학습

DDP 설정

DistributedDataParallel(DDP)이 표준 멀티 GPU 학습 패턴입니다. GPU당 프로세스 하나, 그래디언트가 all-reduce되어 모든 복제본이 동기화됩니다. NVIDIA GPU에서 가장 빠른 백엔드는 nccl입니다. (RANK, WORLD_SIZE, LOCAL_RANK 같은) env 변수 설정은 torchrun이 해 줍니다. 작업이 깨끗히 종료하도록 끝에 항상 dist.destroy_process_group()을 호출하세요. 전체 루프는 gpu-training 섹션입니다.

pytorch
import os, torch
import torch.distributed as dist
import torch.nn as nn

def setup():
    dist.init_process_group(backend='nccl')
    local_rank = int(os.environ['LOCAL_RANK'])
    torch.cuda.set_device(local_rank)
    return local_rank

def cleanup():
    dist.destroy_process_group()

# launch with torchrun
# torchrun --nproc_per_node=4 train.py
# rank, world_size, LOCAL_RANK are set by torchrun

local_rank = setup()
model = model.to(local_rank)
model = nn.parallel.DistributedDataParallel(
    model, device_ids=[local_rank], output_device=local_rank,
)

DistributedSampler

DistributedSampler가 데이터셋을 프로세스에 샤딩해 각 GPU가 각 배치의 고유 하위집합을 봅니다(실효 배치 = batch_size * world_size). 매 에포크 sampler.set_epoch(epoch)을 '반드시' 호출하세요. 없으면 모든 에포크가 같은 셔플을 쓰고 모델이 같은 순서를 봅니다. 샘플러를 쓸 때는 DataLoader에 shuffle=True를 전달하지 마세요. 순서는 샘플러가 다룹니다.

pytorch
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler

sampler = DistributedSampler(
    dataset,
    num_replicas=dist.get_world_size(),
    rank=dist.get_rank(),
    shuffle=True,
    drop_last=True,
)
loader = DataLoader(dataset, batch_size=64, sampler=sampler,
                    num_workers=4, pin_memory=True)

for epoch in range(epochs):
    sampler.set_epoch(epoch)   # reshuffle per epoch
    for x, y in loader:
        # each GPU sees a non-overlapping subset
        ...

멀티 노드 실행

torchrun이 GPU마다 프로세스를 하나 시작해 TCP로 연결합니다. 멀티 노드는 각 노드에서 같은 master_addr과 고유 node_rank로 torchrun을 실행하세요. rendezvous 엔드포인트(--rdzv_endpoint)가 노드들이 서로를 찾게 하며 탄력적 재시작을 지원합니다. master_port가 방화벽에서 열려 있고 모든 노드가 master_addr에 도달할 수 있는지 확인하세요. 좋은 확장을 위해서는 (InfiniBand/NVLink 같은) NCCL에도 고대역폭 인터커넥트가 필요합니다.

pytorch
# single-node, 4 GPUs
torchrun --nproc_per_node=4 train.py

# multi-node (2 nodes, 4 GPUs each = 8 total)
# node 0 (master):
torchrun --nproc_per_node=4 --nnodes=2 --node_rank=0 \
    --master_addr=10.0.0.1 --master_port=29500 train.py

# node 1:
torchrun --nproc_per_node=4 --nnodes=2 --node_rank=1 \
    --master_addr=10.0.0.1 --master_port=29500 train.py

# in code, world_size = nnodes * nproc_per_node
print(dist.get_world_size())   # 8

# also supports elastic restart on node failure
torchrun --nproc_per_node=4 --rdzv_backend=c10d \
    --rdzv_endpoint=10.0.0.1:29500 train.py

그래디언트 동기화

DDP가 그래디언트 all-reduce를 backward 계산과 겹치므로 잘 확장됩니다. 일부 파라미터가 매 스텝 그래디언트를 받지 않을 때(예: 조건 분기) find_unused_parameters=True가 필요하지만 오버헤드가 드니 가능하면 피하세요. 스텝의 동기화 건너뛰기는 model.no_sync()이며 그래디언트 누적과 함께 쓰면 매 마이크로 배치가 아니라 실효 배치당 한 번만 동기화합니다.

pytorch
# DDP all-reduces gradients after backward by default
loss.backward()   # gradients synchronized across GPUs

# skip sync for unused parameters (small speedup)
model = nn.parallel.DistributedDataParallel(
    model, device_ids=[local_rank],
    find_unused_parameters=False,   # set True if some params unused
)

# manual gradient sync (advanced)
for p in model.parameters():
    if p.grad is not None:
        dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)
        p.grad /= dist.get_world_size()

# only sync on the last micro-batch (gradient accumulation)
# use model.no_sync() context for the non-final steps
with model.no_sync():
    loss.backward()

로깅과 체크포인팅

중복과 경쟁 조건을 피하려 로깅과 체크포인팅은 항상 rank==0으로 게이트하세요. DDP 모델 저장에는 model.module.state_dict()를 쓰세요. DDP가 기저 모듈을 감싸며 래퍼를 저장하면 체크포인트가 DDP 전용이 되어 비분산 코드에서 로드가 어렵습니다. 모든 복제본이 같은 가중치로 시작하도록 DDP로 감싸기 전에 모든 rank에서 체크포인트를 로드하세요.

pytorch
# only log from rank 0 to avoid duplicates
if dist.get_rank() == 0:
    writer.add_scalar('train/loss', loss.item(), step)
    print(f'step {step}: loss={loss.item():.4f}')

# only save checkpoint from rank 0
if dist.get_rank() == 0:
    torch.save({
        'model': model.module.state_dict(),   # unwrap DDP
        'optimizer': optimizer.state_dict(),
        'epoch': epoch,
    }, 'ckpt.pt')

# load on all ranks, then wrap with DDP
state = torch.load('ckpt.pt', map_location='cpu')
model.load_state_dict(state['model'])
model = model.to(local_rank)
model = nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])

FullyShardedDataParallel (FSDP)

FSDP가 파라미터, 그래디언트, 옵티마이저 상태를 GPU에 걸쳐 샤딩합니다. 한 GPU에 안 맞는 모델이 여러 GPU에 걸쳐 학습됩니다. (완전 복제본을 유지하는) DDP와 달리 FSDP는 forward/backward 중 수요에 따라 샤드를 모읍니다. 모델이 단일 GPU 메모리에 안 들어갈 때 쓰세요. 저장은 까다롭습니다. state_dict 수집을 FULL_STATE_DICT 모드로 감싸 rank 0이 전체 모델을 머터리얼라이즈하게 하세요. 혼합 정밀도 + FSDP + 활성 체크포인팅으로 매우 큰 모델을 학습할 수 있습니다.

pytorch
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import ShardingStrategy

model = LargeModel().to(local_rank)
model = FSDP(
    model,
    sharding_strategy=ShardingStrategy.FULL_SHARD,
    device_id=local_rank,
    use_orig_params=True,   # needed for save/load compatibility
)

# forward / backward as usual
loss = criterion(model(x), y)
loss.backward()
optimizer.step()

# save: only the full state on rank 0
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
import torch.distributed.fsdp.api as fsdp_api
with FSDP.state_dict_type(model, fsdp_api.StateDictType.FULL_STATE_DICT):
    state = model.state_dict()
    if dist.get_rank() == 0:
        torch.save(state, 'fsdp_ckpt.pt')

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.