PyTorch 파이토치 메모리 용량이 부족할 때

이다언·2024년 12월 20일

PyTorch

목록 보기
2/3

이미지 크기를 224에서 1024로 바꾸었더니
이런 에러가 나왔다

torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB. GPU 0 has a total capacty of 23.69 GiB of which 1.38 GiB is free. Process 308515 has 22.30 GiB memory in use. Of the allocated memory 21.96 GiB is allocated by PyTorch, and 33.94 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

GPT 답변 : 돌아는 가는데, 실행해서 성능(정확도) 측정은 못했습니다. 참고로 보아주세요.

이미지 크기 1024x1024는 매우 큽니다. 이런 고해상도 이미지를 GPU에서 처리하면 메모리 사용량이 급증하기 때문에 CUDA out of memory 오류가 발생하기 쉽습니다.

1024 이미지 처리 시 문제점
1024x1024 이미지는 224x224와 비교해 픽셀이 20배 이상 많습니다.
모델에 입력될 때 특징 맵(Feature Map) 크기와 채널 수가 커져 메모리 사용량이 기하급수적으로 증가합니다.
배치 크기(batch_size)와 모델의 파라미터 수도 메모리 사용량에 큰 영향을 줍니다.
1024 이미지 처리 해결 방법
batch_size를 줄이기
1024 크기 이미지에서는 배치 크기를 아주 작게 설정해야 합니다.

python
코드 복사
BATCH_SIZE = 4 # 아주 작은 배치 크기로 조정
Mixed Precision Training (AMP) 적용
Automatic Mixed Precision은 FP16(반정밀도) 연산을 사용해 메모리 사용량을 줄여줍니다.

python
코드 복사
from torch.cuda.amp import autocast, GradScaler

scaler = GradScaler()
for image, targets in loader:
image, targets = image.to(device), targets.to(device)
optimizer.zero_grad()

with autocast():  # Mixed Precision 사용
    preds = model(image)
    loss = loss_fn(preds, targets)

scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()

이미지 크기 다운샘플링
고해상도 이미지라도 학습에는 해상도를 줄여 사용할 수 있습니다.
예를 들어, 512x512 또는 768x768로 줄이고 테스트 단계에서 고해상도를 사용합니다.

python
코드 복사
img_size = 512 # 1024 대신 512로 줄이기
모델 경량화
EfficientNet 또는 ResNet-18/34처럼 경량 모델을 사용하면 메모리 사용량이 감소합니다.

python
코드 복사
model_name = 'efficientnet_b0' # 메모리 효율적인 모델 사용
Gradient Accumulation
배치 크기를 작게 줄이되, 여러 작은 배치에서 그래디언트를 누적해 학습합니다.

python
코드 복사
accumulation_steps = 4
optimizer.zero_grad()

for i, (image, targets) in enumerate(loader):
image, targets = image.to(device), targets.to(device)
preds = model(image)
loss = loss_fn(preds, targets) / accumulation_steps
loss.backward()

if (i + 1) % accumulation_steps == 0:
    optimizer.step()
    optimizer.zero_grad()

메모리 캐시 비우기
학습 과정 중 GPU 메모리 캐시를 수시로 비워줍니다.

python
코드 복사
import torch
torch.cuda.empty_cache()
num_workers 최적화
데이터 로딩을 효율적으로 조정해서 메모리 사용량을 줄입니다.

python
코드 복사
num_workers = 2 # 필요에 따라 줄여봅니다.
종합 추천
1024 이미지를 학습하려면 아래 순서로 시도하세요:

batch_size를 줄이기 (최소 2~4).
AMP (Mixed Precision) 적용.
이미지 크기 다운샘플링 (예: 512x512).
Gradient Accumulation으로 배치 효과 누적.
모델 경량화 (ResNet-18, EfficientNet-B0 등).
이렇게 하면 GPU 메모리 문제를 해결하면서 1024 크기 이미지도 효율적으로 학습할 수 있을 거예요! 😊

profile
AI 클라우드 웹개발자

0개의 댓글