부스트캠프 AI Tech 2기/2기 U-Stage

3주차 PyTorch Trouble Shooting

모플로 2021. 8. 20. 14:47
반응형

OOM(out of memory)

OOM이 해결하기 어려운 이유

  • 어디서 발생했는지 알기 어려움
  • Error backtracking이 이상한데로 감
  • 메모리의 이전상황의 파악이 어려움

GPU Util 사용하기

  • nvidia-smi 처럼 GPU의 상태를 보여주는 모듈
  • colab은 환경에서 GPU 상태를 보여주기 편함
  • iter마다 메모리가 늘어나는지 확인가능
! pip install GPUtil

import GPUtil
GPUtil.showUtilization()

torch.cuda.empty_cache()써보기

  • 사용되지 않는 GPU상 cache를 정리
  • 가용 메모리를 확보
  • del 과는 구분이 필요
  • reset 대신 쓰기 좋은 함수
  • empty_cache를 사용했을때 강제적으로 garbage collector를 실행
  • 학습전(loop전)에 한번 사용하고 하면 이전학습에서 남아있던 찌꺼기를 제거하고 메모리를 충분히 확보할 수 있다
import torch
from GPUtil import showUtilization as gpu_usage

print("Initial GPU Usage")  
gpu\_usage()

tensorList = \[\]  
for x in range(10):  
tensorList.append(torch.randn(10000000,10).cuda())

print("GPU Usage after allcoating a bunch of Tensors")  
gpu\_usage()

del tensorList  
print("GPU Usage after deleting the Tensors")  
gpu\_usage()

print("GPU Usage after emptying the cache")  
torch.cuda.empty\_cache()  
gpu\_usage()

del 명령어 적절히 사용하기

  • 필요가 없어진 변수는 적절한 삭제가 필요함
  • python의 메모리 배치 특성상 loop 안에서 선언한 변수는 loop이 끝나도 메모리를 차지함

가능한 batch size 실험해보기

  • 학습 시 OOM 이 발생했다면 batch size를 1로 해서 실험해보자
oom = False  
batch\_size = 32  
try:  
run\_model(batch\_size)  
except RuntimeError:  
oom = True

if oom:  
for \_ in range(batch\_size):  
run\_model(1)

torch.no_grad() 사용해보기

  • inference(성능평가) 시점에서는 torch.no_grad() 구문을 사용
  • backward pass 로 인해 쌓이는 메모리에서 자유로움
  • torch no gradient context에서는 backward가 일어나지않음
with torch.no\_grad():  
for data, target in test\_loader:  
output = network(data)  
test\_loss += F.nll\_loss(output, target, size\_average=False).item()  
pred = output.data.max(1, keepdim=True)\[1\]  
correct += pred.eq(target.data.view\_as(pred)).sum()

그 이외의 에러

  • CUDNN_STATUS_NOT_INIT: gpu를 잘못깔았을때 생긴다
  • device-side-assert: oom의 일종으로 생각될 수 있다
  • colab에서 너무 큰사이즈는 실행하지 말것
  • cnn 대부분의 에러는 크기가 안맞아서 생기는 경우가 많음(torchsumamry등으로 사이즈 맞추자)
  • tensor의 float precision을 16bit로 줄일 수 있음 (원래는 32bit)

해당 사이트에 잘 정리가되어있음 => https://brstar96.github.io/shoveling/device_error_summary

```

반응형