关于python:PyTorch模型训练:RuntimeError:cuDNN错误:CUDNN_STATUS_INTERNAL_ERROR

PyTorch Model Training: RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

在GPU上训练PyTorch模型数小时后,程序失败,并显示错误

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

培训条件

  • 神经网络:具有nn.Linear输出的PyTorch 4层nn.LSTM
  • 深度Q网络代理(具有重播内存的Vanilla DQN)
  • 传递到forward()state具有形状(32, 20, 15),其中32是批处理大小
  • 每集50秒
  • 在大约583个事件(8小时)或1,150,000个步骤之后发生错误,其中每个步骤都涉及通过LSTM模型的正向传递。

在训练开始之前,我的代码还设置了以下值

1
2
3
4
torch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(0)

我们如何解决此问题?由于这种情况是在训练的8个小时内发生的,因此在这里进行一些有根据的猜测将非常有帮助!

谢谢!

更新:

注释2条torch.backends.cudnn...行不起作用。 CUDNN_STATUS_INTERNAL_ERROR仍然会发生,但要早于第300集(585,000步)左右。

1
2
3
4
torch.manual_seed(0)
#torch.backends.cudnn.deterministic = True
#torch.backends.cudnn.benchmark = False
np.random.seed(0)

系统

  • PyTorch 1.6.0.dev20200525
  • CUDA 10.2
  • cuDNN 7604
  • Python 3.8
  • Windows 10
  • nVidia 1080 GPU

错误回溯

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
RuntimeError                              Traceback (most recent call last)
<ipython-input-18-f5bbb4fdfda5> in <module>
     57
     58     while not done:
---> 59         action = agent.choose_action(state)
     60         state_, reward, done, info = env.step(action)
     61         score += reward

<ipython-input-11-5ad4dd57b5ad> in choose_action(self, state)
     58         if np.random.random() > self.epsilon:
     59             state = T.tensor([state], dtype=T.float).to(self.q_eval.device)
---> 60             actions = self.q_eval.forward(state)
     61             action = T.argmax(actions).item()
     62         else:

<ipython-input-10-94271a92f66e> in forward(self, state)
     20
     21     def forward(self, state):
---> 22         lstm, hidden = self.lstm(state)
     23         actions = self.fc1(lstm[:,-1:].squeeze(1))
     24         return actions

~\\AppData\\Local\\Continuum\\anaconda3\\envs\
l\\lib\\site-packages\\torch\
n\\modules\\module.py in __call__(self, *input, **kwargs)
    575             result = self._slow_forward(*input, **kwargs)
    576         else:
--> 577             result = self.forward(*input, **kwargs)
    578         for hook in self._forward_hooks.values():
    579             hook_result = hook(self, input, result)

~\\AppData\\Local\\Continuum\\anaconda3\\envs\
l\\lib\\site-packages\\torch\
n\\modules\
nn.py in forward(self, input, hx)
    571         self.check_forward_args(input, hx, batch_sizes)
    572         if batch_sizes is None:
--> 573             result = _VF.lstm(input, hx, self._flat_weights, self.bias, self.num_layers,
    574                               self.dropout, self.training, self.bidirectional, self.batch_first)
    575         else:

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

更新:在我的代码上尝试过try... except发生此错误的地方,除了RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR之外,我们还获得了第二次错误RuntimeError: CUDA error: unspecified launch failure

的回溯

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-4-e8f15cc8cf4f> in <module>
     61
     62     while not done:
---> 63         action = agent.choose_action(state)
     64         state_, reward, done, info = env.step(action)
     65         score += reward

<ipython-input-3-1aae79080e99> in choose_action(self, state)
     58         if np.random.random() > self.epsilon:
     59             state = T.tensor([state], dtype=T.float).to(self.q_eval.device)
---> 60             actions = self.q_eval.forward(state)
     61             action = T.argmax(actions).item()
     62         else:

<ipython-input-2-6d22bb632c4c> in forward(self, state)
     25         except Exception as e:
     26             print('error in forward() with state:', state.shape, 'exception:', e)
---> 27             print('state:', state)
     28         actions = self.fc1(lstm[:,-1:].squeeze(1))
     29         return actions

~\\AppData\\Local\\Continuum\\anaconda3\\envs\
l\\lib\\site-packages\\torch\\tensor.py in __repr__(self)
    152     def __repr__(self):
    153         # All strings are unicode in Python 3.
--> 154         return torch._tensor_str._str(self)
    155
    156     def backward(self, gradient=None, retain_graph=None, create_graph=False):

~\\AppData\\Local\\Continuum\\anaconda3\\envs\
l\\lib\\site-packages\\torch\\_tensor_str.py in _str(self)
    331                 tensor_str = _tensor_str(self.to_dense(), indent)
    332             else:
--> 333                 tensor_str = _tensor_str(self, indent)
    334
    335     if self.layout != torch.strided:

~\\AppData\\Local\\Continuum\\anaconda3\\envs\
l\\lib\\site-packages\\torch\\_tensor_str.py in _tensor_str(self, indent)
    227     if self.dtype is torch.float16 or self.dtype is torch.bfloat16:
    228         self = self.float()
--> 229     formatter = _Formatter(get_summarized_data(self) if summarize else self)
    230     return _tensor_str_with_formatter(self, indent, formatter, summarize)
    231

~\\AppData\\Local\\Continuum\\anaconda3\\envs\
l\\lib\\site-packages\\torch\\_tensor_str.py in __init__(self, tensor)
     99
    100         else:
--> 101             nonzero_finite_vals = torch.masked_select(tensor_view, torch.isfinite(tensor_view) & tensor_view.ne(0))
    102
    103             if nonzero_finite_vals.numel() == 0:

RuntimeError: CUDA error: unspecified launch failure

众所周知,错误RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR很难调试,但是令人惊讶的是,通常这是内存不足的问题。通常,您会遇到内存不足错误,但是根据发生的位置,PyTorch无法拦截该错误,因此无法提供有意义的错误消息。

在您的情况下,可能是内存问题,因为您正在使用while循环,直到代理完成为止,这可能需要很长时间,导致内存用完,这只是时间问题。一旦模型的参数与特定输入的组合无法及时完成,这也可能发生得很晚。

您可以通过限制允许的操作数量来避免这种情况,而不是希望角色在合理的时间内完成。

您还需要注意的是,您不会占用不必要的内存。一个常见的错误是在将来的迭代中继续计算过去状态的梯度。由于当前动作不应影响过去的动作,因此应将最后一次迭代的状态视为常量,因此不需要渐变。这通常是通过将状态从计算图上分离出来进行下一次迭代来实现的,例如下一次迭代。 state = state_.detach()。也许您已经在这样做了,但是如果没有代码,这是不可能的。

同样,如果您保留状态的历史记录,则应分离它们,甚至更重要的是将它们放在CPU中,即history.append(state.detach().cpu())


减少为我工作的num_workers:D


当您使用pytorch的DDP尝试在不使用dist.barrier()的过程中保存模型时,我发现一个案例可能会引发此错误。原因(我想)是:批处理不是在节省时间发布的,而是其他进程尝试读取和加载新批处理。


遇到此错误以及与cudnn / gpu相关的其他错误的任何人都应尝试将模型和输入更改为cpu,通常cpu运行时具有更好的错误报告功能,并使您能够调试问题。

根据我的经验,大多数情况下,错误来自嵌入中的无效索引。


我遇到了同样的问题,并通过将cudatoolkit降级到10.1版来解决了这个问题。因此,尝试使用cudatoolkit 10.1重新安装pytorch。

1
conda install pytorch torchvision cudatoolkit=10.1