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

CPU, CUDA, MPS: 장치와 이동

~14 min · device, cuda, mps, apple-silicon

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

하나의 프레임워크에서 여러 실행 장치를 다뤄

PyTorch는 CPU, NVIDIA CUDA, Apple Silicon MPS를 주요 장치로 지원해. AMD용 ROCm과 Intel용 XPU도 있지만 개인 프로젝트에서는 비교적 덜 흔해. 텐서는 항상 정확히 한 장치에 있고, 같은 연산에 들어가는 입력은 모두 같은 장치에 있어야 해. 장치 사이의 이동에는 .to(device)를 사용해.

장치 문자열을 재사용하는 관용 패턴

대부분의 PyTorch 프로젝트는 사용 가능한 가장 좋은 장치를 고른 뒤 그 문자열을 모델과 데이터 전체에서 재사용하는 코드로 시작해:

device = (
    "cuda" if torch.cuda.is_available()
    else "mps" if torch.backends.mps.is_available()
    else "cpu"
)

이 문자열을 모델과 모든 배치의 .to(device)에 넘겨. 'expected cuda:0 got cpu' 오류는 대개 장치로 옮기지 않은 텐서 하나에서 시작돼.

MPS: Apple Silicon 실행 장치

MPS는 표준 연산 대부분을 지원하지만 아직 지원하지 않는 연산도 있어. 이런 연산을 CPU 대체 경로로 실행하려면 PYTORCH_ENABLE_MPS_FALLBACK=1을 설정해야 하고, 사용할 때는 경고가 나타날 수 있어. MPS의 torch.compile 지원은 계속 개선되고 있지만 CUDA만큼 성숙하지는 않아. Apple Silicon에서 최고 성능이 필요하다면 처음부터 통합 메모리를 중심으로 설계된 MLX가 더 적합할 때가 있어.

Code

장치 감지와 기본 패턴·python
import torch

print(torch.cuda.is_available())          # True if NVIDIA GPU
print(torch.backends.mps.is_available())  # True on Apple Silicon
print(torch.cuda.device_count())          # number of CUDA GPUs

device = (
    "cuda" if torch.cuda.is_available()
    else "mps" if torch.backends.mps.is_available()
    else "cpu"
)
print(f"Using {device}")
텐서와 모델 이동·python
import torch
import torch.nn as nn

device = "mps"  # or whatever you picked

# Tensors
x = torch.randn(32, 100)            # CPU
x = x.to(device)                     # moves
print(x.device)                      # mps:0

# Create directly on device — avoids the CPU→device copy
y = torch.randn(32, 100, device=device)

# Models — to() moves all parameters AND buffers
model = nn.Linear(100, 10).to(device)

# Inputs and weights MUST be on the same device
out = model(y)   # works
# out = model(torch.randn(32, 100))  # RuntimeError: device mismatch
페이지 고정 메모리와 non_blocking으로 GPU 학습 가속하기·python
import torch
from torch.utils.data import DataLoader

# In your DataLoader, set pin_memory=True
# (only meaningful when you'll move data to a CUDA GPU)
loader = DataLoader(dataset, batch_size=64, num_workers=4, pin_memory=True)

device = "cuda"
for x, y in loader:
    # non_blocking=True lets the CPU keep going while the copy queues
    x = x.to(device, non_blocking=True)
    y = y.to(device, non_blocking=True)
    # ...training step...

External links

Exercise

성능 측정 코드를 작성해. 사용할 수 있는 각 장치에 (4096, 4096) 텐서 두 개를 만들고 행렬 곱셈을 10번 실행해 시간을 재. Apple Silicon에서는 MLX로도 같은 작업을 측정해 비교하고 결과를 기록해 둬.

Progress

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

댓글 0

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

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