🤖 AI/ML

GPU

Graphics Processing Unit

A processor specialized for parallel computation. Essential for deep learning training and inference. NVIDIA CUDA is the standard.

📖 Detailed Explanation

GPU (Graphics Processing Unit) was originally designed for graphics rendering, but thanks to its parallel computing capability using thousands of cores, it has become the core hardware of deep learning. While CPUs specialize in complex sequential computation, GPUs are optimized for processing simple operations simultaneously at massive scale.

The reason GPUs are essential in deep learning is matrix operations. The forward propagation and backpropagation of neural networks consist of large-scale matrix multiplications, which the thousands of cores of a GPU process simultaneously. For example, the NVIDIA H100 is equipped with 16,896 CUDA cores and 528 Tensor cores, delivering 1.98 PFLOPS of performance at FP16.

NVIDIA dominates the market for AI GPUs. Representative examples include the H100 (80GB HBM3) for data centers, the A100 (40GB/80GB HBM2e) for research, and the RTX 4090 (24GB GDDR6X) for consumers. AMD's MI300X and Intel's Gaudi are also competing, and in the cloud, AWS, GCP, and Azure all offer these GPUs.

In practice, VRAM is the key factor when choosing a GPU. LLM training requires storing the model parameters, optimizer states, and gradients all together, so full fine-tuning of a 7B model requires about 56GB of VRAM. Inference requires far less, but even a 7B model needs about 14GB in FP16. When configuring multiple GPUs, NVLink bandwidth is also important.

💻 Code Example

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)

🗣️ Say It Like This in Practice

Technical Interview Scenario

"What GPU do I need to train a 7B model?" - "For full fine-tuning, you need at least two A100 80GB cards. The model takes 14GB and the optimizer states take 42GB, so 56GB is required, and once you factor in activation memory, a single GPU isn't enough. With LoRA, a single RTX 4090 24GB card can do it."

Project Meeting

"Cloud GPU vs. on-premises, which is better?" - "For experimental stages or workloads with high variability, the cloud is more flexible. But if you need 24/7 training, on-premises is more cost-effective. A single H100 costs $4 per hour in the cloud, and you'd recoup the purchase cost in about 18 months. However, also consider the costs of cooling, power, and management staff."

Code Review

"I keep getting CUDA out of memory errors. What should I do?" - "First, clear the cache with torch.cuda.empty_cache(), and turning on gradient checkpointing can reduce activation memory. Reducing the batch size or using mixed precision (FP16/BF16) is also effective. If that still doesn't work, use gradient accumulation to maintain the effective batch size while reducing the actual batch size."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Beware of Confusing VRAM with RAM

GPU VRAM and system RAM are different. Even if you have 64GB of RAM, you can't load a large model if the GPU VRAM is 8GB. Monitor real-time VRAM usage with nvidia-smi.

2
Heat and Throttling

Performance degrades when the GPU temperature exceeds 80 degrees. During long training runs, check the cooling status, and proper air conditioning systems are essential for data center GPUs.

3
Driver Compatibility

Check the compatibility between the CUDA version and the PyTorch/TensorFlow version. The latest CUDA is not always better, and you should use a version supported by the framework.

🔗 Related Terms

📚 Learn More