Joonas' Note

Joonas' Note

[PyTorch] GPU 메모리가 부족할 때 확인할 내용들 본문

AI/딥러닝

[PyTorch] GPU 메모리가 부족할 때 확인할 내용들

2022. 4. 25. 21:08 joonas

    https://github.com/pytorch/pytorch/issues/16417

     

    RuntimeError: CUDA out of memory. Tried to allocate 12.50 MiB (GPU 0; 10.92 GiB total capacity; 8.57 MiB already allocated; 9.28

    CUDA Out of Memory error but CUDA memory is almost empty I am currently training a lightweight model on very large amount of textual data (about 70GiB of text). For that I am using a machine on a c...

    github.com

    대부분 아래 메시지를 받는다.

    CUDA out of memory. Tried to allocate 196.50 MiB (GPU 0; 15.75 GiB total capacity; 7.09 GiB already allocated; 20.62 MiB free; 72.48 MiB cached)

    최근 겪은 일이고, 텐서가 GPU가 계속 묶여있어서 메모리 해제가 안되서 생긴 일 같다.
    그런데 노트북에서 임시 객체로 생성하는 것을 반복하다보니, 직접 변수를 찾아서 해제할수도 없는 상황이었다.

    대표적인 몇가지 해결 방법들이 있는 것 같은데, 시간이 날 때마다 저 이슈의 스레드를 다 확인해보면 좋겠다.

    1. 커널 재시작

    주피터 노트북이나 Kaggle, Colab 등의 환경이라면, 커널을 재시작해서 GPU 자원을 초기화시킬 수 있다.

    그런데 이 방법은, 저장했던 변수들이 다 날아가므로... 재부팅해서 해결하는 사례로 보인다.

    2. 변수 확인

    GPU를 잡고 있는데, 더 이상 사용하지 않는 변수들을 직접 찾아서 제거한다.

    2-1. 변수 제거

    a = torch.zero(10, dtype=torch.int8, device='cuda')
    del a

    2-2. tolist()

    model.to('cuda')
    # outputs = model(inputs)
    outputs = model(inputs).tolist()
    TORCH.TENSOR.TOLIST
    Tensor.tolist() → list or numberReturns the tensor as a (nested) list. For scalars, a standard Python number is returned, just like with item(). Tensors are automatically moved to the CPU first if necessary.
    https://pytorch.org/docs/stable/generated/torch.Tensor.tolist.html

    2-3. 자동 미분 끄기

    with torch.no_grad():
        # code here

    3. Batch size

    @balcilar commented on 2 Jun 2019
    It is because of mini-batch of data does not fit on to GPU memory. Just decrease the batch size. When I set batch size = 256 for cifar10 dataset I got the same error; Then I set the batch size = 128, it is solved.
    https://github.com/pytorch/pytorch/issues/16417#issuecomment-497952224

    네트워크에 따라서 배치 사이즈를 줄이면 해결될 수도 있다.
    극단적으로 batch size를 1로 줄여서 해결하는 사람들도 있다 (....)

    4. 네트워크 크기

    뉴럴 넷의 크기를 줄인다. 레이어 사이의 추적되는 weights와 biases를 줄인다는 뜻 같다. 그래서 pretrained는 해당되지 않는 내용 같음.

    5. torch.cuda의 함수 호출

    사용하지는 않지만 캐시에 할당된 자원들을 끊는다. 그래서 다른 GPU에서는 사용할 수 있다.
    그리고 fragmenation을 줄이는 함수이지, GPU 메모리의 가용량을 늘리는 함수는 아니므로 오해하면 안된다.

     torch.cuda.empty_cache()

    https://pytorch.org/docs/stable/generated/torch.cuda.empty_cache.html

    6. Garbage Collect

    import gc
    gc.collect()​

    Garbage Collector를 수동으로 실행시켜서 메모리를 해제시킨다.

     

     

     

    Comments