[python] gpu(cuda) 프로세스 정리하기

2023. 9. 12. 18:43·컴퓨터구조 & OS

CUDA를 사용하는 프로세스 종료하기

저희 flask 서버에서는 gpu를 사용하는 모델을 2개 돌립니다.
- spleeter (mr제거)
- cnn 분류기
 
spleeter 작업 후 cnn분류기가 연이어 있습니다.
문제는 spleeter가 끝나더라도 gpu 메모리가 곧장 내려가지는 않습니다.
정리해줘야 합니다. Out Of Memory가 잘 터지기 때문이죠!
 
그래서 gpu 정리 기능을 추가했습니다.
gpu 점유 프로세스를 모두 정리하는 코드입니다.
(의도치않은 gpu 프로세스가 종료되지 않는지 검토하고 사용해야 합니다.)
(cpu 환경에서는 CudaAPIError가 터지기 때문에, 아무 것도 안하도록 예외처리했습니다.)

from numba import cuda
from numba.cuda.cudadrv.devices import CudaAPIError

# gpu 메모리 완전 정리
def clean_gpu():
    try:
        device = cuda.get_current_device()
        device.reset()
    except CudaAPIError:
        # CPU 모드에서는 정리할 것이 없다
        pass

현재 작업중인 cuda device에 대한 정보가 나옵니다. 간단하게는 device를 print해보면 gpu명이 나옵니다. 
예를 들면 <CUDA device 0 'b'NVIDIA GeForce MX450''> 이렇게.. 
 
 
참고) Cpu환경에서의 CudaAPIError

더보기
---------------------------------------------------------------------------
CudaAPIError                              Traceback (most recent call last)
c:\Users\kye33\Desktop\mr_remover_test\mr_remover_test.ipynb Cell 8 line 9
      6     print(device)
      7     device.reset()
----> 9 clean_gpu()

c:\Users\kye33\Desktop\mr_remover_test\mr_remover_test.ipynb Cell 8 line 5
      4 def clean_gpu():
----> 5     device = cuda.get_current_device()
      6     print(device)
      7     device.reset()

File c:\Users\kye33\miniconda3\envs\gpuenv\lib\site-packages\numba\cuda\api.py:443, in get_current_device()
    441 def get_current_device():
    442     "Get current device associated with the current thread"
--> 443     return current_context().device

File c:\Users\kye33\miniconda3\envs\gpuenv\lib\site-packages\numba\cuda\cudadrv\devices.py:220, in get_context(devnum)
    216 def get_context(devnum=None):
    217     """Get the current device or use a device by device number, and
    218     return the CUDA context.
    219     """
--> 220     return _runtime.get_or_create_context(devnum)
...
    397 if retcode == enums.CUDA_ERROR_NOT_INITIALIZED:
    398     self._detect_fork()
--> 399 raise CudaAPIError(retcode, msg)

CudaAPIError: [2] Call to cuDevicePrimaryCtxRetain results in CUDA_ERROR_OUT_OF_MEMORY

 
 
사용 예시!
gpu 정리가 필요한 곳에 배치했습니다.

 
 
효과가 있는 모습입니다.
OOM 문제를 해결했습니다. 끝!
 

 
 

'컴퓨터구조 & OS' 카테고리의 다른 글

[운영체제] 프로세스 상태도  (2) 2023.09.28
[운영체제] 프로세스 스케줄링: 멀티프로그래밍 vs 타임쉐어링  (0) 2023.09.27
[Nvidia][Docker] 컨테이너에서 GPU 돌리기!  (0) 2023.09.09
Linux gpu 세팅[2] | 기존 컨테이너에서 GPU 사용하도록 변경하기  (2) 2023.09.08
[WSL와 VM의 차이점] 하이퍼바이저를 이해하며..  (2) 2023.09.07
'컴퓨터구조 & OS' 카테고리의 다른 글
  • [운영체제] 프로세스 상태도
  • [운영체제] 프로세스 스케줄링: 멀티프로그래밍 vs 타임쉐어링
  • [Nvidia][Docker] 컨테이너에서 GPU 돌리기!
  • Linux gpu 세팅[2] | 기존 컨테이너에서 GPU 사용하도록 변경하기
히어로맛쿠키
히어로맛쿠키
  • 히어로맛쿠키
    yeny_lab
    히어로맛쿠키
  • 전체
    오늘
    어제
    • 분류 전체보기 (389)
      • 미분류글 (32)
        • ㅇ (2)
      • JAVA (84)
        • Effective Java (1)
        • Application (21)
      • 컴퓨터구조 & OS (28)
      • 자료구조 + 알고리즘 (43)
      • Database (12)
      • 컴파일러 (10)
      • 수학 (33)
        • 미분방정식 (12)
      • 데이터분석과 머신러닝 (38)
      • 기타 (59)
      • yyeeennyy (25)
  • 공지사항

    • ^o^/♡
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
히어로맛쿠키
[python] gpu(cuda) 프로세스 정리하기
상단으로

티스토리툴바