CUDA out of memory 해결

siwoo·2024년 2월 14일

오류해결

목록 보기
3/3

recbole library를 사용해 작업을 하던 중

RuntimeError: CUDA out of memory. Tried to allocate 39.77 GiB (GPU 0; 31.75 GiB total capacity; 1.54 GiB already allocated; 20.91 GiB free; 1.56 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

라는 에러가 발생했다.

일단 처음에는 torch.cuda.empty_cache(), 중간중간 필요 없어진 텐서를 del하는 방식을 썼는데 아주 조금 저장공간의 여유가 생기기만 하고 궁극적인 에러는 해결되지 않았다.

예측 코드 중간 중간에 메모리 용량 변화를 보려고 예약된 메모리, 캐시된 메모리 용량 변화를 확인해봤다.

allocated = torch.cuda.memory_allocated()
cached = torch.cuda.memory_cached()

print("현재 할당된 GPU 메모리:", allocated / 1024 ** 3, "GB")
print("캐시된 GPU 메모리:", cached / 1024 ** 3, "GB")

오류가 난 코드 부근에서 갑자기 예약된 메모리 용량이 급격하게 커지는 것 같았다.
삭제할 수 없는 텐서였기 때문에 결국은 데이터 자체를 분할해서 예측하는 것밖에 답이 없다는 생각이 들었다.

그래서 원래 한번에 모든 테스트 유저에 대한 예측을 수행하는 방식에서 분할해서 예측하는 방식으로 오픈 소스코드를 수정한 결과 inference가 성공적으로 수행되는 것을 확인하였다.

0개의 댓글