PyTorch에서 autocast를 사용하는 방법
이 글에서는 짧은 튜토리얼을 통해 텐서 자동 캐스팅을 구현하는 방법을 코드와 대화형 시각화와 함께 살펴봅니다. 직접 따라 하실 수 있습니다. 이 글은 AI 번역본입니다. 오역이 의심되면 댓글로 알려주세요.
Created on September 15|Last edited on September 15
Comment
이 글에서는 여러분이 사용하는 방법을 살펴봅니다 torch.cuda.amp.autocast() 계산 효율적인 학습 루프를 작성하기 위해 PyTorch에서 자동 텐서 캐스팅을 구현하기.
PyTorch에서 제공하는 다양한 혼합 정밀도 방법을 자세히 살펴보려면 다음을 참조하세요 공식 문서를 참조하세요.
💡
목차
코드부터 보기
대부분의 PyTorch 학습 루프는 다음과 같은 형태입니다:
optimizer = ...for epoch in range(...):for i, sample in enumerate(dataloader):inputs, labels = sampleoptimizer.zero_grad()# Forward Passoutputs = model(inputs)# Compute Loss and Perform Back-propagationloss = loss_fn(outputs, labels)loss.backward()# Update Optimizeroptimizer.step()
또한 PyTorch로 딥러닝 모델, 특히 대규모 언어 모델(LLM)을 한동안 학습해 보셨다면, 다음과 같은 CUDA 오류를 한 번쯤은 겪어 보셨을 것입니다:
RuntimeError: CUDA out of memory. Tried to allocate .. MiB (.. GiB total capacity; ... GiB already allocated;... MiB free; ... GiB reserved in total by PyTorch)
CUDA 메모리 부족(OOM) 오류를 방지하는 방법에 대한 보다 자세한 개요는 아래 보고서를 참조하시기 바랍니다.
Preventing The CUDA Out Of Memory Error In PyTorch
A short tutorial on how you can avoid the "RuntimeError: CUDA out of memory" error while using the PyTorch framework.
How To Use GradScaler in PyTorch
In this article, we explore how to implement automatic gradient scaling (GradScaler) in a short tutorial complete with code and interactive visualizations.
대규모 딥러닝 모델을 학습할 때 자주 발생하는 OOM 오류의 가장 흔한 원인 중 하나는 메모리 활용 문제입니다. 기본적으로 PyTorch는 모델 파라미터를 float32로 저장합니다. 규모가 조금만 커져도 상당한 메모리를 차지합니다. 예를 들어 16 GB RAM을 가진 괜찮은 가속기가 있어도, 더 큰 모델은 학습하기 어려울 수 있습니다. 심지어 하나의 배치에 대해 단 한 번의 순전파조차 계산하지 못할 수도 있습니다. 이 문제에 대한 한 가지 해결책은 텐서를 자동으로 더 작은 메모리 형식으로 캐스팅하는 것입니다. 예를 들어 float16이나 심지어 정수 타입으로요! 꽤 간단해 보이지 않나요?
한 줄의 코드로 Autocast를 사용하는 방법을 살펴보겠습니다!
optimizer = ...for epoch in range(...):for i, sample in enumerate(dataloader):inputs, labels = sampleoptimizer.zero_grad()# ⭐️ ⭐️ Autocastingwith torch.cuda.amp.autocast():# Forward Passoutputs = model(inputs)# Compute Loss and Perform Back-propagationloss = loss_fn(outputs, labels)loss.backward()# Update Optimizeroptimizer.step()
W&B로 메트릭을 기록할 때마다 몇 초 간격으로 매우 많은 시스템 메트릭이 함께 수집됩니다. 이를 통해 우리 머신에서 어떤 일이 일어나고 있는지 유용한 인사이트를 얻을 수 있습니다. 기록되는 메트릭의 전체 목록은 여기에서 확인할 수 있습니다.
여기서는 메모리 부족(OOM) 문제를 해결하는 것이 목표입니다. Weights & Biases가 유용한 메트릭을 어떻게 추적하는지 차트를 통해 살펴보겠습니다:
Run set
보시다시피 대부분의 실행에서 메모리 할당과 GPU 활용도가 92%–95%까지 올라갑니다. Autocast를 사용해 이를 줄여 볼 수 있습니다.
요약
이 글에서는 여러분이 어떻게 사용할 수 있는지 살펴보았습니다 torch.cuda.amp.autocast() PyTorch에서 자동 텐서 캐스팅을 활용해 계산 효율적인 학습 루프를 구현하고, Weights & Biases로 메트릭을 모니터링하여 유용한 인사이트를 얻는 방법.
W&B의 모든 기능을 확인하려면 다음을 참조하세요 짧은 5분 가이드수학적 내용과 처음부터 구현한 코드까지 포함한 더 많은 리포트를 원하신다면, 아래 댓글이나 저희의 채널에서 알려주세요 포럼 ✨!
추천 자료
Preventing The CUDA Out Of Memory Error In PyTorch
A short tutorial on how you can avoid the "RuntimeError: CUDA out of memory" error while using the PyTorch framework.
How To Use GradScaler in PyTorch
In this article, we explore how to implement automatic gradient scaling (GradScaler) in a short tutorial complete with code and interactive visualizations.
Setting Up TensorFlow And PyTorch Using GPU On Docker
A short tutorial on setting up TensorFlow and PyTorch deep learning models on GPUs using Docker.
PyTorch Dropout for regularization - tutorial
Learn how to regularize your PyTorch model with Dropout, complete with a code tutorial and interactive visualizations
How to Initialize Weights in PyTorch
A short tutorial on how you can initialize weights in PyTorch with code and interactive visualizations.
How To Use GPU with PyTorch
A short tutorial on using GPUs for your deep learning models with PyTorch, from checking availability to visualizing usable.
Add a comment