Pytorch: Vazamento de memória CUDA?

Criado em 11 abr. 2017  ·  3Comentários  ·  Fonte: pytorch/pytorch

from torch.autograd import Variable
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
cudnn.benchmark = True

import sys
print('__Python VERSION:', sys.version)
print('__pyTorch VERSION:', torch.__version__)
print('__CUDA VERSION')
from subprocess import call
call(["nvcc", "--version"])
print('__CUDNN VERSION:', torch.backends.cudnn.version())
print('__Number CUDA Devices:', torch.cuda.device_count())
print('__Devices')
call(["nvidia-smi", "--format=csv", "--query-gpu=index,name,driver_version,memory.total,memory.used,memory.free"])
print('Active CUDA Device: GPU', torch.cuda.current_device())
# print('  Try to change to Device 2 - with "torch.cuda.device(2)"')
# torch.cuda.device(2)
# print('  ! Active CUDA Device is still:', torch.cuda.current_device())
#
# print('  Try again with environment vars')
# import os
# os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"]="2"
# print('  ! Active CUDA Device is still:', torch.cuda.current_device())

import time
from torch.nn import Conv1d as Conv1d

num_runs = 10
s = 5*22050

print('\n')
for seqlen in [s]:
    for batch_size in [16, 32]:
        for dilation in reversed([64, 128, 256, 512]):
            m = nn.Sequential(Conv1d(32, 32, kernel_size=2, dilation=dilation),
                              Conv1d(32, 32, kernel_size=2, dilation=dilation),
                              Conv1d(32, 32, kernel_size=2, dilation=dilation),
                              Conv1d(32, 32, kernel_size=2, dilation=dilation),
                              Conv1d(32, 32, kernel_size=2, dilation=dilation)).cuda()
            input = torch.randn(batch_size, 32, seqlen).float().cuda()

            torch.cuda.synchronize()
            start = time.time()
            for j in range(num_runs):
                output = m(Variable(input, requires_grad=True))
                output.backward(output.data)
            torch.cuda.synchronize()
            mean_time = (time.time() - start) / float(num_runs)
            print('batch_size: %i\tdilation: %i\tseqlen: %i\t time %f\t runs: %i' %(batch_size, dilation, seqlen, mean_time, num_runs))

Saída:

__Python VERSION: 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 12:22:00) 
__pyTorch VERSION: 0.1.11+8aa1cef
__CUDA VERSION
Cuda compilation tools, release 8.0, V8.0.61
__CUDNN VERSION: 6020
__Number CUDA Devices: 4
__Devices
index, name, driver_version, memory.total [MiB], memory.used [MiB], memory.free [MiB]
0, GeForce GTX 1080 Ti, 381.09, 11158 MiB, 318 MiB, 10840 MiB
1, GeForce GTX 1080 Ti, 381.09, 11172 MiB, 11 MiB, 11161 MiB
2, GeForce GTX 1080 Ti, 381.09, 11172 MiB, 11 MiB, 11161 MiB
3, GeForce GTX 1080 Ti, 381.09, 11172 MiB, 11 MiB, 11161 MiB
Active CUDA Device: GPU 0

batch_size: 16  dilation: 512   seqlen: 110250   time 0.204314   runs: 10
batch_size: 16  dilation: 256   seqlen: 110250   time 0.162138   runs: 10
batch_size: 16  dilation: 128   seqlen: 110250   time 0.148690   runs: 10
batch_size: 16  dilation: 64    seqlen: 110250   time 0.141783   runs: 10
batch_size: 32  dilation: 512   seqlen: 110250   time 0.279548   runs: 10
Traceback (most recent call last):
  File "benchmark_test.py", line 48, in <module>
    output = m(Variable(input, requires_grad=True))
  File "/home/USERNAME/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/USERNAME/anaconda3/lib/python3.6/site-packages/torch/nn/modules/container.py", line 64, in forward
    input = module(input)
  File "/home/USERNAME/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/USERNAME/anaconda3/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 143, in forward
    self.padding, self.dilation, self.groups)
  File "/home/USERNAME/anaconda3/lib/python3.6/site-packages/torch/nn/functional.py", line 62, in conv1d
    return f(input, weight, bias)
RuntimeError: CUDNN_STATUS_ALLOC_FAILED

Eu queria saber por que recebi o CUDNN_STATUS_ALLOC_FAILED.
Depois de alguns experimentos descobri que - erro ou não - depende da sequência na lista de dilatação:
linha 37: for dilation in reversed([64, 128, 256, 512]):
A execução sem reversed ocorre sem erros.

Eu ainda não estou familiarizado com a coisa toda. Eu estou faltando alguma coisa?

--
Felizmente adaptei este código de #967.
A propósito: também estou curioso por que não posso alterar o dispositivo CUDA ativo (veja o comentário no código)…

Comentários muito úteis

Por favor, tente executar com cudnn.benchmark=False. cudnn.benchmark não está fazendo nenhum bem para convoluções dilatadas de qualquer maneira.

Todos 3 comentários

Por favor, tente executar com cudnn.benchmark=False. cudnn.benchmark não está fazendo nenhum bem para convoluções dilatadas de qualquer maneira.

Oi,
Você deve usar torch.cuda.set_device(2) para alterar a GPU que você usa ou:

with torch.cuda.device(2):
    # do stuff on gpu 2
# Back on the default GPU

Além disso, o CUDA_VISIBLE_DEVICES só afetará a execução se for definido antes de iniciar o script.

Uau, obrigado pelas respostas rápidas e muito precisas!

@ngimel : Nunca pensei nisso... Usar cudnn.benchmark=False resolveu. Não importa o tamanho da lista que eu tentei. O erro não apareceu novamente.

@albanD : Isso também! Eu não usei set_device() porque seu documento afirma que é desencorajado em favor de device(). Estranho.

Esta página foi útil?
0 / 5 - 0 avaliações

Questões relacionadas

cdluminate picture cdluminate  ·  3Comentários

szagoruyko picture szagoruyko  ·  3Comentários

soumith picture soumith  ·  3Comentários

NgPDat picture NgPDat  ·  3Comentários

soumith picture soumith  ·  3Comentários