与形状张量分配时OOM:了解ResourceExhaustedError

问题描述 投票:6回答:4

我试图用tensorflow实现跳跃思维模式和当前版本放置hereenter image description here

目前,我用我的机器的一个GPU(共2个GPU)和GPU的信息是

2017-09-06 11:29:32.657299: I tensorflow/core/common_runtime/gpu/gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 1080 Ti
major: 6 minor: 1 memoryClockRate (GHz) 1.683
pciBusID 0000:02:00.0
Total memory: 10.91GiB
Free memory: 10.75GiB

然而,我当我试图把数据反馈给模型OOM。我尝试调试如下:

我用下面的代码片段之后我跑sess.run(tf.global_variables_initializer())

    logger.info('Total: {} params'.format(
        np.sum([
            np.prod(v.get_shape().as_list())
            for v in tf.trainable_variables()
        ])))

如果全部采用2017-09-06 11:29:51,333 INFO main main.py:127 - Total: 62968629 params得到240Mb,大致约tf.float32tf.global_variables的输出是

[<tf.Variable 'embedding/embedding_matrix:0' shape=(155229, 200) dtype=float32_ref>,
 <tf.Variable 'encoder/rnn/gru_cell/gates/kernel:0' shape=(400, 400) dtype=float32_ref>,
 <tf.Variable 'encoder/rnn/gru_cell/gates/bias:0' shape=(400,) dtype=float32_ref>,
 <tf.Variable 'encoder/rnn/gru_cell/candidate/kernel:0' shape=(400, 200) dtype=float32_ref>,
 <tf.Variable 'encoder/rnn/gru_cell/candidate/bias:0' shape=(200,) dtype=float32_ref>,
 <tf.Variable 'decoder/weights:0' shape=(200, 155229) dtype=float32_ref>,
 <tf.Variable 'decoder/biases:0' shape=(155229,) dtype=float32_ref>,
 <tf.Variable 'decoder/previous_decoder/rnn/gru_cell/gates/kernel:0' shape=(400, 400) dtype=float32_ref>,
 <tf.Variable 'decoder/previous_decoder/rnn/gru_cell/gates/bias:0' shape=(400,) dtype=float32_ref>,
 <tf.Variable 'decoder/previous_decoder/rnn/gru_cell/candidate/kernel:0' shape=(400, 200) dtype=float32_ref>,
 <tf.Variable 'decoder/previous_decoder/rnn/gru_cell/candidate/bias:0' shape=(200,) dtype=float32_ref>,
 <tf.Variable 'decoder/next_decoder/rnn/gru_cell/gates/kernel:0' shape=(400, 400) dtype=float32_ref>,
 <tf.Variable 'decoder/next_decoder/rnn/gru_cell/gates/bias:0' shape=(400,) dtype=float32_ref>,
 <tf.Variable 'decoder/next_decoder/rnn/gru_cell/candidate/kernel:0' shape=(400, 200) dtype=float32_ref>,
 <tf.Variable 'decoder/next_decoder/rnn/gru_cell/candidate/bias:0' shape=(200,) dtype=float32_ref>,
 <tf.Variable 'global_step:0' shape=() dtype=int32_ref>]

在我的训练句话,我有一个数据数组,其形状为(164652, 3, 30),即sample_size x 3 x time_step3在这里是指前面的句子,当前句子和下一个句子。这个训练数据的大小约为57Mb并存储在一个loader。然后我用写一个生成函数来获得句子,看起来像

def iter_batches(self, batch_size=128, time_major=True, shuffle=True):

    num_samples = len(self._sentences)
    if shuffle:
        samples = self._sentences[np.random.permutation(num_samples)]
    else:
        samples = self._sentences

    batch_start = 0
    while batch_start < num_samples:
        batch = samples[batch_start:batch_start + batch_size]

        lens = (batch != self._vocab[self._vocab.pad_token]).sum(axis=2)
        y, x, z = batch[:, 0, :], batch[:, 1, :], batch[:, 2, :]
        if time_major:
            yield (y.T, lens[:, 0]), (x.T, lens[:, 1]), (z.T, lens[:, 2])
        else:
            yield (y, lens[:, 0]), (x, lens[:, 1]), (z, lens[:, 2])
        batch_start += batch_size

培训圈的样子

for epoch in num_epochs:
    batches = loader.iter_batches(batch_size=args.batch_size)
    try:
        (y, y_lens), (x, x_lens), (z, z_lens) =  next(batches)
        _, summaries, loss_val = sess.run(
        [train_op, train_summary_op, st.loss],
        feed_dict={
            st.inputs: x,
            st.sequence_length: x_lens,
            st.previous_targets: y,
            st.previous_target_lengths: y_lens,
            st.next_targets: z,
            st.next_target_lengths: z_lens
        })
    except StopIteraton:
        ...

然后,我得到了一个OOM。如果我注释掉整个try体(无养活数据),脚本运行就好了。

我不知道为什么我在这样一个小规模的数据得到了OOM。使用nvidia-smi我总是有

Wed Sep  6 12:03:37 2017
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.59                 Driver Version: 384.59                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 108...  Off  | 00000000:02:00.0 Off |                  N/A |
|  0%   44C    P2    60W / 275W |  10623MiB / 11172MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+
|   1  GeForce GTX 108...  Off  | 00000000:03:00.0 Off |                  N/A |
|  0%   43C    P2    62W / 275W |  10621MiB / 11171MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID  Type  Process name                               Usage      |
|=============================================================================|
|    0     32748    C   python3                                      10613MiB |
|    1     32748    C   python3                                      10611MiB |
+-----------------------------------------------------------------------------+

我看不到我的脚本的实际GPU使用,因为总是tensorflow抢断开头的所有记忆。这里实际的问题是我不知道如何调试这一点。

我读过有关StackOverflow上OOM一些帖子。他们中的大多数喂大的测试集数据模型,并通过喂养小批量的数据能够避免此类问题发生时。但我不为什么看到我的11GB 1080Ti这么小的数据和param组合很烂,因为错误,它只是尝试分配矩阵大小[3840 x 155229]。 (解码器的输出矩阵,3840 = 30(time_steps) x 128(batch_size)155229是vocab_size)。

2017-09-06 12:14:45.787566: W tensorflow/core/common_runtime/bfc_allocator.cc:277] ********************************************************************************************xxxxxxxx
2017-09-06 12:14:45.787597: W tensorflow/core/framework/op_kernel.cc:1158] Resource exhausted: OOM when allocating tensor with shape[3840,155229]
2017-09-06 12:14:45.788735: W tensorflow/core/framework/op_kernel.cc:1158] Resource exhausted: OOM when allocating tensor with shape[3840,155229]
     [[Node: decoder/previous_decoder/Add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](decoder/previous_decoder/MatMul, decoder/biases/read)]]
2017-09-06 12:14:45.790453: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:247] PoolAllocator: After 2857 get requests, put_count=2078 evicted_count=1000 eviction_rate=0.481232 and unsatisfied allocation rate=0.657683
2017-09-06 12:14:45.790482: I tensorflow/core/common_runtime/gpu/pool_allocator.cc:259] Raising pool_size_limit_ from 100 to 110
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1139, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1121, in _run_fn
    status, run_metadata)
  File "/usr/lib/python3.6/contextlib.py", line 88, in __exit__
    next(self.gen)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[3840,155229]
     [[Node: decoder/previous_decoder/Add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](decoder/previous_decoder/MatMul, decoder/biases/read)]]
     [[Node: GradientDescent/update/_146 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_2166_GradientDescent/update", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

任何帮助将不胜感激。提前致谢。

tensorflow tensorflow-gpu
4个回答
15
投票

让我们从一个分裂的问题之一:

关于tensorflow提前分配所有的内存,你可以用下面的代码片段,让tensorflow每当需要的时候分配内存。这样就可以了解的事情进展。

gpu_options = tf.GPUOptions(allow_growth=True)
session = tf.InteractiveSession(config=tf.ConfigProto(gpu_options=gpu_options))

如果你喜欢这与tf.Session()代替tf.InteractiveSession()同样适用。

关于大小第二件事情,至于有没有关于网络大小的信息,我们不能估计什么错误。但是,您可以或者调试一步一步的所有网络。例如,创建一个网络只用一层,得到它的输出,创建会话和一次喂值和可视化你多少内存消耗。直到看到你要去哪里出内存点迭代此调试会话。

请注意,3840 X 155229输出是真的,确实是一个大的输出。这意味着〜600M神经元,和〜每只有一层2.22GB。如果您有任何类似的尺寸层,所有的人都会加起来非常快填补你的GPU内存。

此外,这是仅适用于前进方向,如果要使用该层进行训练,通过优化加入反向传播和层将2。所以相乘这个大小,对训练你消耗〜5 GB只是为输出层。

我建议你修改你的网络,并尽量减少批量大小/参数计算,以适应你的模型GPU


6
投票

这可能是没有意义技术上,经历过了一段时间后,这是我已经找到了。

环境:Ubuntu的16.04


When you run the command

NVIDIA-SMI

您将得到安装的Nvidia图形卡的总内存消耗。所示那样在该图像enter image description here一个例子

当你运行你的神经网络的消费可能会改变看起来像enter image description here

内存消耗通常被给予蟒。由于一些奇怪的原因,如果这个过程中未能成功终止,记忆永远不会被释放。如果您尝试运行的神经网络应用的另一个实例,你是布特收到内存分配错误。难的方法是试图想出一个办法来终止使用进程ID这一过程。例如,进程ID为2794,你可以做

sudo kill -9 2794

最简单的方法,是刚刚重新启动计算机,然后再试一次。如果是代码相关的bug但是,这是不行的。


1
投票

您正在耗尽你的内存,您可以减少批量大小,这会减慢训练过程,但让你拟合数据。


-4
投票

重新启动jupyter笔记本电脑工作对我来说

© www.soinside.com 2019 - 2024. All rights reserved.