分配器(GPU_0_bfc)在使用纯张量流时尝试分配内存不足,而在 keras 上更复杂的模型上没有错误

Posted

技术标签:

【中文标题】分配器(GPU_0_bfc)在使用纯张量流时尝试分配内存不足,而在 keras 上更复杂的模型上没有错误【英文标题】:Allocator (GPU_0_bfc) ran out of memory trying to allocate when using pure tensorflow vs no error on more complex model on keras 【发布时间】:2020-02-02 14:49:22 【问题描述】:

我正在使用 nvidia gforce 1050 ti

我在 keras 中有一个模型,它工作正常,没有出现内存分配错误 但是当我在 tensorflow 中运行一个更简单的模型时 我得到错误打击, 查看错误:在这篇文章中找到错误==== 查看 tf 模型:找到 TENSORFLOW=== 查看 keras 模型:find KERAS===

我不明白这一点,因为批量大小(128)是相同的 我有 tensorflow-gpu(安装了 pip) 那么为什么 keras 运行良好(具有更复杂的模型)而 tensorflow 却没有?

谢谢!

2019-10-04 11:45:58.450155: W tensorflow/core/common_runtime/bfc_allocator.cc:237] 分配器 (GPU_0_bfc) 在尝试分配 freed_by_count=0 的 1.83GiB 时内存不足。调用者表示这不是失败,但可能意味着如果有更多内存可用,可能会提高性能。 2019-10-04 11:45:58.450838: W tensorflow/core/common_runtime/bfc_allocator.cc:237] 分配器 (GPU_0_bfc) 在尝试分配 freed_by_count=0 的 2.84GiB 时内存不足。调用者表示这不是失败,但可能意味着如果有更多内存可用,可能会提高性能。 2019-10-04 11:46:08.451808: W tensorflow/core/common_runtime/bfc_allocator.cc:314] 分配器 (GPU_0_bfc) 试图分配 1.22GiB(四舍五入为 1310720000)时内存不足。当前分配摘要如下。 2019-10-04 11:46:08.452025:I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (256):总块:33,正在使用的块:33。为块分配了 8.3KiB。 8.3KiB 在 bin 中使用。 2.6KiB 客户端请求在 bin 中使用。 2019-10-04 11:46:08.452239: I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (512): Total Chunks: 0, Chunks in use: 0. 0B 分配给块。 0B 在 bin 中使用。 0B 客户端请求在 bin 中使用。 2019-10-04 11:46:08.452436:I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (1024):总块:1,正在使用的块:1。为块分配了 1.3KiB。 1.3KiB 在 bin 中使用。 1.0KiB 客户端请求在 bin 中使用。 2019-10-04 11:46:08.452648: I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (2048): Total Chunks: 0, Chunks in use: 0. 0B 分配给块。 0B 在 bin 中使用。 0B 客户端请求在 bin 中使用。 2019-10-04 11:46:08.452854:I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (4096):总块:9,使用中的块:9。为块分配了 44.0KiB。 44.0KiB 在 bin 中使用。 44.0KiB 客户端请求在 bin 中使用。 2019-10-04 11:46:08.453073: I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (8192): Total Chunks: 0, Chunks in use: 0. 0B 分配给块。 0B 在 bin 中使用。 0B 客户端请求在 bin 中使用。 2019-10-04 11:46:08.453276: I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (16384): Total Chunks: 0, Chunks in use: 0. 0B 分配给块。 0B 在 bin 中使用。 0B 客户端请求在 bin 中使用。 2019-10-04 11:46:08.453482:I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (32768):总块:4,正在使用的块:4。为块分配了 160.0KiB。 160.0KiB 在 bin 中使用。 160.0KiB 客户端请求在 bin 中使用。 2019-10-04 11:46:08.453706:I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (65536):总块:5,正在使用的块:5。为块分配了 384.0KiB。 384.0KiB 在 bin 中使用。 334.1KiB 客户端请求在 bin 中使用。 2019-10-04 11:46:08.453934:I tensorflow/core/common_runtime/bfc_allocator.cc:764] Bin (131072):总块:4,正在使用的块:4。为块分配了 512.0KiB。 512.0KiB 在 bin 中使用。 512.0KiB 客户端请求在 bin 中使用。

张量流:

x = tf.placeholder(tf.float32,shape=[None,32,32,3])
y = tf.placeholder(dtype=tf.float32,shape=[None,CLASSES])
keep_prob = tf.placeholder(dtype=tf.float32)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
conv1c,rlu1c,max1 = createConvBlock(x,filters=32)
conv2c,rlu2c,max2 = createConvBlock(max1,filters=64)
conv3c,rlu3c,max3 = createConvBlock(max2,filters=128)
conv3c,rlu3c,max3 = createConvBlock(max3,filters=128)
flat = flatten(max3)
dropout = dense(flat,1024,True,keep_prob)
dw4,db4= dense(dropout,CLASSES)
y_hat = tf.matmul(dropout,dw4)+db4
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=y_hat))
train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cross_entropy)
BATCH = 128

class CifarHelper():

    def __init__(self):
        self.i = 0
        (train_x, train_y), (test_x, test_y) = tf.keras.datasets.cifar10.load_data()

        self.all_train_batches = train_x
        self.test_batch = test_x

        self.training_images = train_x / 255
        self.training_labels = to_onehot(train_y,10)

        self.test_images = test_x / 255
        self.test_labels = to_onehot(test_y,10)



    def next_batch(self, batch_size):
        x = self.training_images[self.i:self.i + batch_size]
        y = self.training_labels[self.i:self.i + batch_size]
        self.i = (self.i + batch_size) % len(self.training_images)
        return x, y


ch = CifarHelper()
with tf.Session(config=config) as sess:
    sess.run(tf.global_variables_initializer())
    for i in tqdm(range(EPOCHES)):
        a,b = ch.next_batch(BATCH)
        train_step.run(feed_dict=x: a,y :b,keep_prob: 1.0)
        if i % 100 == 0:
            matches = tf.equal(tf.argmax(y_hat, 1), tf.argmax(y, 1))

            acc = tf.reduce_mean(tf.cast(matches, tf.float32))

            test_acc[i//100] = sess.run(acc, feed_dict=x: ch.test_images, y: ch.test_labels, keep_prob: 1.0)



def createConvBlock(xinput,filters,stride = 1,withMaxPoll=True,pool_kernel=[1,2,2,1],pool_stride=[1,2,2,1]):
    shape = [s.value for s in xinput.get_shape()]
    shape = [3,3,shape[3],filters]
    wtb = tf.truncated_normal(shape=shape, stddev=0.1)
    w = tf.Variable(wtb)
    b = tf.Variable(tf.constant(0.1, dtype=tf.float32, shape=[filters]))
    conv = tf.nn.conv2d(xinput,w,strides=[1,stride,stride,1],padding='SAME')
    rlu = tf.nn.relu(conv + b)
    if withMaxPoll:
        maxpool = tf.nn.max_pool2d(rlu,ksize=pool_kernel,strides=pool_stride,padding='SAME')
        return conv,rlu,maxpool

    return conv, rlu

def flatten(layer):
    pooling_size = np.product([s.value for s in layer.get_shape()[1:]])
    flat = tf.reshape(layer,shape=[-1,pooling_size])
    print('flatt '.format(flat.get_shape()))
    return flat


def dense(layer,filters,withDropouts = False,keep_prob = None):
    shape = [s.value for s in layer.get_shape()[1:]] + [filters]
    norm = np.product(shape)
    w = tf.Variable(
        tf.truncated_normal(shape=shape, stddev=0.1))
    b = tf.Variable(tf.constant(0.1, dtype=tf.float32, shape=[filters]))
    z = tf.nn.relu(tf.matmul(layer, w) + b)

    if withDropouts:
        dropout = tf.nn.dropout(z,keep_prob)
        return dropout
    return w,b

Keras:

batch_size = 128
num_classes = 10
epochs = 5

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(LeakyReLU())
model.add(Conv2D(32,kernel_size=(3,3),padding='SAME'))
model.add(LeakyReLU())
model.add(Conv2D(32,kernel_size=(3,3),padding='SAME'))
model.add(LeakyReLU())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3),name='cnv',padding='SAME'))
model.add(LeakyReLU())
model.add(Conv2D(64, (3, 3),padding='SAME'))
model.add(LeakyReLU())
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(128, (3, 3),padding='SAME'))
model.add(LeakyReLU())
model.add(Conv2D(128, (3, 3),padding='SAME'))
model.add(LeakyReLU())
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024))
model.add(LeakyReLU())
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax', name='preds'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adam(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))

【问题讨论】:

【参考方案1】:

您应该减少批量大小。如果仍然不起作用,请检查您的代码批量大小为 64 ,将其减少到 32 或 16 或 8 。这会导致epoch的执行时间增加。

【讨论】:

正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。 又是怎么回事?第二个模型更复杂,两个模型的批量大小都是 128,这根本不能回答我的问题

以上是关于分配器(GPU_0_bfc)在使用纯张量流时尝试分配内存不足,而在 keras 上更复杂的模型上没有错误的主要内容,如果未能解决你的问题,请参考以下文章

TensorFlow 内存不足

如何安装张量流显卡?

安装张量流时出错

为 GPU 编译张量流示例自定义操作

Colab 提供 OOM 用于在 tensorflow 中在 GPU 上分配 4.29 GB 张量

小白入门PyTorch | 第一篇:什么是PyTorch?