首页 > 解决方案 > 使用 TensorFlow Eager Execution 和 tf.keras 时警告“试图解除分配 nullptr”

问题描述

根据 tensorflow 团队的建议,我已经习惯了 tensorflow 对 tf.keras 的急切执行。然而,每当我训练一个模型时,我都会收到一个警告(编辑:实际上,我收到这个警告重复了很多次,每个训练步骤不止一次,淹没了我的标准输出):

E tensorflow/core/common_runtime/bfc_allocator.cc:373] tried to deallocate nullptr

该警告似乎不会影响培训的质量,但我想知道它的含义以及是否有可能摆脱它。

我使用在 CPU 上运行 python 3.7 和 tensorflow 1.12 的 conda 虚拟环境。(编辑:使用 python 3.6 进行的测试给出了相同的结果。)下面是重现警告的最小代码。有趣的是,可以评论 tf.enable_eager_execution() 行并看到警告消失。

import numpy as np
import tensorflow as tf

tf.enable_eager_execution()
N_EPOCHS = 50
N_TRN = 10000
N_VLD = 1000

# the label is positive if the input is a number larger than 0.5
# a little noise is added, just for fun
x_trn = np.random.random(N_TRN)
x_vld = np.random.random(N_VLD)
y_trn = ((x_trn + np.random.random(N_TRN) * 0.02) > 0.5).astype(float)
y_vld = ((x_vld + np.random.random(N_VLD) * 0.02) > 0.5).astype(float)

# a simple logistic regression
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_dim=1))
model.add(tf.keras.layers.Activation('sigmoid'))

model.compile(
    optimizer=tf.train.AdamOptimizer(),
    # optimizer=tf.keras.optimizers.Adam(),  # doesn't work at all with tf eager execution
    loss='binary_crossentropy',
    metrics=['accuracy']
)

# Train model on dataset
model.fit(
    x_trn, y_trn,
    epochs=N_EPOCHS,
    validation_data=(x_vld, y_vld),
)
model.summary()

标签: pythontensorflowkeraseager-execution

解决方案


快速解决方案:

  • 当我在 TF 1.11 中运行相同的脚本时,它没有出现,同时执行优化以在合成数据集上达到相同的最终验证精度。

    或者

  • 使用本机 os 模块(改编自https://stackoverflow.com/a/38645250/2374160)抑制错误/警告。IE; 通过将 Tensorflow 日志记录环境变量设置为不显示任何错误消息。

      import os
      os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
      import tensorflow as tf
    

更多信息:

  • 以正确的方式解决此错误可能需要熟悉 MKL 库调用及其在用 C 编写的 Tensorflow 上的接口(这超出了我目前的 TF 专业知识)

  • 就我而言,每当调用优化器的apply_gradients()方法时,都会发生此内存释放错误 。在您的脚本中,当模型适合训练数据时调用它。

  • 从这里引发此错误:tensorflow/core/common_runtime/mkl_cpu_allocator.h

我希望这有助于作为方便的临时解决方案。


推荐阅读