Python tf.keras即使在批量为1的小型LSTM模型上也是如此

Python tf.keras即使在批量为1的小型LSTM模型上也是如此,python,tensorflow,keras,tensorflow-datasets,tensorflow2.0,Python,Tensorflow,Keras,Tensorflow Datasets,Tensorflow2.0,从TensorFlow 1.5迁移到TensorFlow 2.0时,我遇到了这个错误。我想特别声明,此型号在1.5上运行正常。唯一改变的是在feed.fit()时从生成器(顺便说一句,批量大小为8)迁移到tf.Dataset 我已经研究了很多关于GPU上OOM问题的堆栈溢出线程,但是,大多数都是关于真正巨大的张量的问题,而我的是一个小的[256128]或大批量的问题 这是我的模型: def build_model(self): self.g_Model = Sequential()

从TensorFlow 1.5迁移到TensorFlow 2.0时,我遇到了这个错误。我想特别声明,此型号在1.5上运行正常。唯一改变的是在feed.fit()时从生成器(顺便说一句,批量大小为8)迁移到tf.Dataset

我已经研究了很多关于GPU上OOM问题的堆栈溢出线程,但是,大多数都是关于真正巨大的张量的问题,而我的是一个小的[256128]或大批量的问题

这是我的模型:

def build_model(self):
    self.g_Model = Sequential()
    self.g_Model.add(Embedding(input_dim=self.g_Max_features, output_dim=256, name='X'))
    self.g_Model.add(LSTM(128))
    self.g_Model.add(Dropout(0.5))
    self.g_Model.add(Dense(1, activation='sigmoid'))
    self.g_Model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
总结:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
X (Embedding)                (None, None, 256)         256000    
_________________________________________________________________
lstm (LSTM)                  (None, 128)               197120    
_________________________________________________________________
dropout (Dropout)            (None, 128)               0         
_________________________________________________________________
dense (Dense)                (None, 1)                 129       
=================================================================
Total params: 453,249
Trainable params: 453,249
Non-trainable params: 0
以下是我的列车功能:

def train_model(self):
    if self.g_Model is None:
        self.build_model()

    dataset = self.prepare_the_data()
    self.g_Model.fit(dataset, epochs=2)
以及数据本身的准备:

@staticmethod
def prepare_the_data():
    lstm_feature_description = {
        'X_input': tf.io.FixedLenFeature(CONFIG.g_keras_lstm_max_document_length, tf.float32),
        'y': tf.io.FixedLenFeature((), tf.int64),
    }

    def _parse_lstm_function(example_proto):
        # Parse the input tf.Example proto using the dictionary above.
        parsed = tf.io.parse_single_example(serialized=example_proto, features=lstm_feature_description)
        return parsed["X_input"], parsed["y"]

    # Start Preparing The Data
    dataset = tf.data.TFRecordDataset(CONFIG.g_record_file_lstm)
    dataset = dataset.shuffle(buffer_size=5000)
    dataset = dataset.map(map_func=_parse_lstm_function)
    dataset = dataset.batch(batch_size=1)

    for next_element in dataset:
        tf.print(next_element)

    return dataset
数据集包含40个元素。下面是其中一个的样子:

([[0 0 0 ... 1 10 3]], [0])
X_输入是一个大小为24000的tensorflow.python.framework.ops.tensor,y是相同的类型,但大小为1(只是一个标签)

因此,在运行.fit()时,我收到以下OOM错误(第1部分):

第2部分:

2019-11-02 18:44:43.211483: I tensorflow/core/common_runtime/bfc_allocator.cc:917] 1 Chunks of size 525056 totalling 512.8KiB
2019-11-02 18:44:43.211607: I tensorflow/core/common_runtime/bfc_allocator.cc:917] 1 Chunks of size 1047808 totalling 1023.3KiB
2019-11-02 18:44:43.211731: I tensorflow/core/common_runtime/bfc_allocator.cc:921] Sum Total of in-use chunks: 2.06GiB
2019-11-02 18:44:43.211851: I tensorflow/core/common_runtime/bfc_allocator.cc:923] total_region_allocated_bytes_: 2210712576 memory_limit_: 2210712780 available bytes: 204 curr_region_allocation_bytes_: 4294967296
2019-11-02 18:44:43.212060: I tensorflow/core/common_runtime/bfc_allocator.cc:929] Stats: 
Limit:                  2210712780
InUse:                  2210712576
MaxInUse:               2210712576
NumAllocs:                  137751
MaxAllocSize:             33554432

2019-11-02 18:44:43.216115: W tensorflow/core/common_runtime/bfc_allocator.cc:424] ****************************************************************************************************
2019-11-02 18:44:43.216331: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at split_op.cc:311 : Resource exhausted: OOM when allocating tensor with shape[256,128] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
2019-11-02 18:44:43.216642: W tensorflow/core/common_runtime/base_collective_executor.cc:216] BaseCollectiveExecutor::StartAbort Resource exhausted: OOM when allocating tensor with shape[256,128] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
     [[{{node sequential/lstm/while/body/_1/split}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

     [[Reshape_12/_28]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

2019-11-02 18:44:43.223629: W tensorflow/core/common_runtime/base_collective_executor.cc:216] BaseCollectiveExecutor::StartAbort Resource exhausted: OOM when allocating tensor with shape[256,128] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
     [[{{node sequential/lstm/while/body/_1/split}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
我已经试过了,但运气不好:

  • 我已经设置了记忆增长=真
  • 从列车功能中删除了所有代码,除了构建 model和.fit()本身
  • 将批量大小降低到1

  • 我真的不明白发生了什么,因为我的模型很小,批量大小只有1。我使用的是GTX1060 3GB。因此,非常感谢您的帮助。谢谢

    你不会相信我的错误有多愚蠢。在@OverLordGoldDragon发布了不同的问答之后,我才幸运地认出了它

    在导入阶段,我使用了以下语句:

    from tensorflow_core.python.keras.layers import Dense, Dropout, LSTM, Embedding
    from tensorflow_core.python.keras.models import Sequential, load_model
    from tensorflow_core.python.keras.preprocessing import sequence
    
    相反,我应该用这些:

    from tensorflow.keras.layers import Dense, Dropout, LSTM, Embedding
    from tensorflow.keras.models import Sequential, load_model
    from tensorflow.keras.preprocessing import sequence
    
    顺便说一句,最新的PyCharm Professional没有为tf.keras语句提供自动完成功能,这让我一开始就拒绝了。出人意料的是,tf.python.keras auto completetion工作正常


    更多信息可在此处找到:

    请参阅;此外,还应确保CUDA和cuDNN安装正确,且版本与TF 2.0.0兼容。作为临时解决方法,请尝试
    tf.compat.v1.disable\u eager\u execution()
    我已经尝试过tf.compat.v1.disable\u eager\u execution()。不幸的是,我的情况也是如此。关于CUDA和cuDNN版本:我正在使用CUDA 10.0.130和cuDNN 7.6.4.38。如果有什么不同的话,我还安装了TensorRT 6.0.1.5。CUDA/cuDNN建议不是一个微不足道的建议;这决定了很多。您正在运行哪些版本,以及如何安装它们(通过package manager或从源代码构建)?我在编辑栏中列出了上述版本。我正在运行Win10,所以我已经使用NVIDIA安装程序(CUDA)安装了它们,并且cuDNN是从NVIDIA提供的存档中手动复制的;您是否能够开发和构建CUDA示例解决方案(不是全部,而是大部分)?此外,列出的一些官方步骤将抛出错误,但可以忽略。整个过程对我来说是一团糟,但作为最后一步,Anaconda再次将cudatoolkit安装到其环境中以使其正常工作-我可能会一步一步地写下这一点,但在此之前,您的案例肯定有问题,CUDA安装可能是罪魁祸首。哦,孩子。我应该记得问过以防万一-是的,
    tf.python
    充满了烟火。如果问题现在解决了,请考虑对链接问题的答案进行投票。(顺便问一句,你是怎么想到那个问答的?我在这里都没提到)
    from tensorflow.keras.layers import Dense, Dropout, LSTM, Embedding
    from tensorflow.keras.models import Sequential, load_model
    from tensorflow.keras.preprocessing import sequence