본문 바로가기
C.W.K.
Stream
Lesson 04 of 08 · published

Mixed Precision, Gradient Accumulation, 메모리

~26 min · training, memory, amp

Level 0스카우트
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

지원 장치에서는 bf16부터 검토해

bf16=True를 켜면 순전파와 역전파의 activation·gradient는 bf16으로 계산하고 optimizer용 기준 가중치는 fp32로 유지해. Ampere 이후 하드웨어에서는 품질 손실을 거의 늘리지 않으면서 속도와 메모리를 개선할 수 있어.

gradient accumulation은 메모리를 시간으로 바꿔

GPU에 예제 4개만 들어가지만 유효 batch 64가 필요하면 장치별 batch를 4, 누적 단계를 16으로 설정해. 16개 microbatch의 gradient를 모은 뒤 한 번 갱신하므로 결과적인 batch는 같지만 step마다 계산 시간이 늘어.

  • gradient_checkpointing=True는 activation을 다시 계산해 메모리를 줄이고 속도를 희생해.
  • optim='adamw_8bit'는 optimizer 상태를 8비트로 저장해.
  • torch.compile(model)은 모양이 안정적일 때 빨라질 수 있지만 동적 모양에서는 오히려 손해일 수 있어.

Code

메모리 효율 TrainingArguments·python
from transformers import TrainingArguments

args = TrainingArguments(
    output_dir="./out",
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,   # effective batch = 16 (single GPU)
    bf16=True,
    gradient_checkpointing=True,
    optim="adamw_8bit",              # bitsandbytes 필요
    num_train_epochs=3,
    learning_rate=2e-4,
    warmup_ratio=0.03,
    lr_scheduler_type="cosine",
    save_steps=500, eval_steps=500, logging_steps=50,
    torch_compile=False,             # baseline 동작 후 True 시도
)
학습 중 peak 메모리 inspect·python
import torch

# Peak counter reset
torch.cuda.reset_peak_memory_stats()

# ... 일부 step trainer.train() 실행 ...

print(f"peak: {torch.cuda.max_memory_allocated() / 1e9:.2f} GB")

External links

Exercise

너 IMDB Trainer 셋업 가져와. 세 번 돌려: (1) 디폴트 fp32, (2) bf16, (3) bf16 + gradient_checkpointing + adamw_8bit. 각각 peak GPU 메모리 + step latency 측정. 트레이드오프 곡선 메모.

Progress

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

댓글 0

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

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