Skip to main content
PyTorch에서 GradScaler를 사용하는 방법
이 글에서는 자동 그래디언트 스케일링(GradScaler)을 구현하는 방법을 코드와 대화형 시각화를 곁들인 짧은 튜토리얼 형태로 살펴봅니다. 이 글은 AI 번역본입니다. 오역이 있을 수 있으니 댓글로 알려 주세요.
Last updated: September 15, 2025
이 글에서는 여러분이 사용할 수 있는 방법을 살펴봅니다 torch.cuda.amp.GradScaler 에서 PyTorch 연산 효율적인 훈련 루프를 작성하기 위해 자동 그래디언트 스케일링을 구현하기.
TensorFlow와 달리 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()
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 오류를 방지하는 방법에 대한 훨씬 더 자세한 개요는 다음 보고서를 참조하세요:
대규모 딥러닝 모델에서 흔히 발생하는 오류 중 하나는 그래디언트 언더플로(즉, 그래디언트가 너무 작아 계산에서 무시되는 문제)입니다. float16 텐서는 극도로 작은 변화를 반영하지 못하는 경우가 자주 있습니다.
이를 방지하기 위해 그래디언트에 어떤 스케일 팩터를 곱해 0으로 소거되지 않도록 할 수 있습니다. 이는 그래디언트 소실과 혼동하면 안 되며, 이러한 그래디언트는 학습에 기여할 수 있지만 계산 정밀도의 한계 때문에 건너뛰어지는 경우입니다.
이제 훈련 루프에서 GradScaler를 사용하는 방법을 살펴보겠습니다:
scaler = torch.cuda.amp.GradScaler()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)# ⭐️ ⭐️ Scale Gradientsscaler.scale(loss).backward()# ⭐️ ⭐️ Update Optimizerscaler.step(optimizer)scaler.update()
더 잘 이해하려면 다음 영상을 참고하세요:
요약
이 글에서는 다음과 같이 활용하는 방법을 살펴보았습니다 torch.cuda.amp.GradScaler PyTorch에서 자동 그래디언트 스케일링을 구현해 연산 효율적인 훈련 루프를 작성하는 방법과, Weights & Biases를 사용해 지표를 모니터링함으로써 가치 있는 인사이트를 얻는 방법
추천 자료
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.
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 Compare Keras Optimizers in Tensorflow for Deep Learning
A short tutorial outlining how to compare Keras optimizers for your deep learning pipelines in Tensorflow, with a Colab to help you follow along.
How to Initialize Weights in PyTorch
A short tutorial on how you can initialize weights in PyTorch with code and interactive visualizations.
Recurrent Neural Network Regularization With Keras
A short tutorial teaching how you can use regularization methods for Recurrent Neural Networks (RNNs) in Keras, with a Colab to help you follow along.
How To Calculate Number of Model Parameters for PyTorch and TensorFlow Models
This article provides a short tutorial on calculating the number of parameters for TensorFlow and PyTorch deep learning models, with examples for you to follow.
Add a comment
If using Gradscalar, how does this affect the gradients that are logged using wandb.watch()? Is there a way to log the unscaled, rather than scaled, gradients?
Reply
Hey there, Thanks for the article. Referring to this tutorial: https://pytorch.org/tutorials/recipes/recipes/amp_recipe.html GradScaler usage is bound to use the torch.autocast().
Reply