🤖 AI/ML

GPU

Graphics Processing Unit

병렬 연산에 특화된 프로세서. 딥러닝 학습과 추론에 필수적. NVIDIA CUDA가 표준.

📖 상세 설명

GPU(Graphics Processing Unit)는 원래 그래픽 렌더링용으로 설계되었지만, 수천 개의 코어를 활용한 병렬 연산 능력 덕분에 딥러닝의 핵심 하드웨어가 되었습니다. CPU가 복잡한 순차 연산에 특화된 반면, GPU는 단순한 연산을 대규모로 동시에 처리하는 데 최적화되어 있습니다.

딥러닝에서 GPU가 필수인 이유는 행렬 연산 때문입니다. 신경망의 순전파와 역전파는 대규모 행렬 곱셈으로 구성되며, 이를 GPU의 수천 개 코어가 동시에 처리합니다. 예를 들어 NVIDIA H100은 16,896개의 CUDA 코어와 528개의 Tensor 코어를 탑재하여 FP16 기준 1.98 PFLOPS의 성능을 제공합니다.

AI용 GPU는 NVIDIA가 시장을 지배하고 있습니다. 데이터센터용 H100(80GB HBM3), 연구용 A100(40GB/80GB HBM2e), 소비자용 RTX 4090(24GB GDDR6X)이 대표적입니다. AMD의 MI300X와 Intel의 Gaudi도 경쟁하고 있으며, 클라우드에서는 AWS, GCP, Azure 모두 이들 GPU를 제공합니다.

실무에서 GPU 선택은 VRAM이 핵심입니다. LLM 학습에는 모델 파라미터, 옵티마이저 상태, 그래디언트를 모두 저장해야 하므로 7B 모델 풀 파인튜닝에 약 56GB VRAM이 필요합니다. 추론은 훨씬 적게 들지만, 7B 모델도 FP16으로 약 14GB가 필요합니다. 멀티 GPU 구성 시 NVLink 대역폭도 중요합니다.

💻 코드 예제

import torch

# GPU 사용 가능 여부 확인
print(f"CUDA available: {torch.cuda.is_available()}")
print(f"GPU count: {torch.cuda.device_count()}")
print(f"Current device: {torch.cuda.current_device()}")
print(f"Device name: {torch.cuda.get_device_name(0)}")

# GPU 메모리 확인
def print_gpu_memory():
    allocated = torch.cuda.memory_allocated() / 1024**3
    reserved = torch.cuda.memory_reserved() / 1024**3
    total = torch.cuda.get_device_properties(0).total_memory / 1024**3
    print(f"Allocated: {allocated:.2f} GB")
    print(f"Reserved: {reserved:.2f} GB")
    print(f"Total: {total:.2f} GB")

# 모델을 GPU로 이동
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = torch.nn.Linear(1000, 1000).to(device)
data = torch.randn(128, 1000).to(device)

# GPU 연산 수행
with torch.cuda.amp.autocast():  # Mixed Precision
    output = model(data)

# 멀티 GPU 학습 (DataParallel)
if torch.cuda.device_count() > 1:
    model = torch.nn.DataParallel(model)
    print(f"Using {torch.cuda.device_count()} GPUs")

# 더 효율적인 멀티 GPU: DistributedDataParallel
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP

# 초기화 (torchrun 사용 권장)
# torchrun --nproc_per_node=4 train.py
def setup_ddp(rank, world_size):
    dist.init_process_group("nccl", rank=rank, world_size=world_size)
    torch.cuda.set_device(rank)

# CUDA 캐시 정리 (OOM 방지)
torch.cuda.empty_cache()

# GPU 벤치마크
import time

def benchmark_gpu(size=10000, iterations=100):
    a = torch.randn(size, size, device='cuda')
    b = torch.randn(size, size, device='cuda')

    torch.cuda.synchronize()  # GPU 동기화
    start = time.time()

    for _ in range(iterations):
        c = torch.matmul(a, b)

    torch.cuda.synchronize()
    elapsed = time.time() - start

    flops = 2 * size**3 * iterations
    tflops = flops / elapsed / 1e12
    print(f"Matrix size: {size}x{size}")
    print(f"Time: {elapsed:.2f}s, TFLOPS: {tflops:.2f}")

# nvidia-smi 정보를 Python에서 조회
import subprocess
result = subprocess.run(['nvidia-smi', '--query-gpu=name,memory.used,memory.total,utilization.gpu',
                        '--format=csv,noheader'], capture_output=True, text=True)
print(result.stdout)

🗣️ 실무에서 이렇게 말하세요

기술 면접 상황

"7B 모델을 학습하려면 어떤 GPU가 필요한가요?" - "풀 파인튜닝이면 A100 80GB가 최소 2장 필요합니다. 모델 14GB, 옵티마이저 상태 42GB로 56GB가 필요하고 활성화 메모리까지 고려하면 단일 GPU로는 부족해요. LoRA를 쓰면 RTX 4090 24GB 1장으로도 가능합니다."

프로젝트 회의

"클라우드 GPU vs 온프레미스, 어떤 게 나을까요?" - "실험 단계나 변동성이 큰 워크로드는 클라우드가 유연합니다. 하지만 24/7 학습이 필요하면 온프레미스가 비용 효율적이에요. H100 한 장이 클라우드에서 시간당 $4인데, 18개월 정도면 구매 비용을 회수합니다. 다만 냉각, 전력, 관리 인력 비용도 고려하세요."

코드 리뷰

"CUDA out of memory 에러가 자주 나는데 어떻게 해야 하나요?" - "우선 torch.cuda.empty_cache()로 캐시를 정리하고, gradient checkpointing을 켜면 활성화 메모리를 줄일 수 있어요. 배치 사이즈를 줄이거나 mixed precision(FP16/BF16)도 효과적입니다. 그래도 안 되면 gradient accumulation으로 effective batch size를 유지하면서 실제 배치는 줄이세요."

⚠️ 흔한 실수 & 주의사항

1
VRAM과 RAM 혼동 주의

GPU VRAM과 시스템 RAM은 다릅니다. 64GB RAM이 있어도 GPU VRAM이 8GB면 큰 모델을 로드할 수 없습니다. nvidia-smi로 실시간 VRAM 사용량을 모니터링하세요.

2
발열과 스로틀링

GPU 온도가 80도를 넘으면 성능이 저하됩니다. 장시간 학습 시 냉각 상태를 확인하고, 데이터센터용 GPU는 적절한 공조 시스템이 필수입니다.

3
드라이버 호환성

CUDA 버전과 PyTorch/TensorFlow 버전의 호환성을 확인하세요. 최신 CUDA가 항상 좋은 것은 아니며, 프레임워크에서 지원하는 버전을 사용해야 합니다.

🔗 관련 용어

📚 더 배우기