keras 关于使用多个 gpu

最近参加了一个图像比赛,因为是第一次使用 GPU 跑深度学习并且用的是 以 tensorflow 为后端的 keras 框架,遇到了一个很严重的问题,导致了前期训练时间翻了一倍,差一点就能进复赛,很可惜。

一开始的时候,老师跟我说,我使用电脑的时候,全都是 CPU 的声音,GPU 没得到有效地使用,我不以为意,因为我运行程序的时候显示了
这里写图片描述
很明显,我已经使用了电脑仅有的两个 GPU 。。。
然后运行 nvidia-smi 显示了两个 GPU 显存是占满的,诶,不对呀,为什么只有一个 GPU 在计算,另一个利用率为 0 % ???
原来,我整个比赛都只是使用了一半的计算资源。。。天呐,我才真正意识到,这下坑队友了!

还有就是,keras 默认是占满所有显存,这时候其他的进程就无法使用 GPU 资源了即使keras 实际上用不完,这个时候就需要设置 keras 使用显存的大小了

keras 设置显存 按比例 / 按需 分配

import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5 #比例
#or
config.gpu_options.allow_growth = True #按需
set_session(tf.Session(config=config))

指定使用的 GPU

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"

或者在命令行运行时指定

CUDA_VISIBLE_DEVICES=0,1 python keras_demo.py

以为指定了多个 GPU keras 就使用多个GPU? 太天真了
下面是 keras 使用 多GPU 的解决方法,
文章写得非常棒,我是搬运工,原链接:
https://www.jianshu.com/p/db0ba022936f

References.
官方文档:multi_gpu_model
以及Google

  1. 误区
    目前Keras是支持了多个GPU同时训练网络,非常容易,但是靠以下这个代码是不行的。

当你监视GPU的使用情况(nvidia-smi -l 1)的时候会发现,尽管GPU不空闲,实质上只有一个GPU在跑,其他的就是闲置的占用状态,也就是说,如果你的电脑里面有多张显卡,无论有没有上面的代码,Keras都会默认的去占用所有能检测到的GPU。这行代码在你只需要一个GPU的时候时候用的,也就是可以让Keras检测不到电脑里其他的GPU。假设你一共有三张显卡,每个显卡都是有自己的标号的(0, 1, 2),为了不影响别人的使用,你只用其中一个,比如用gpu=1的这张,那么

os.environ["CUDA_VISIBLE_DEVICES"] = "1"

然后再监视GPU的使用情况(nvidia-smi -l 1),确实只有一个被占用,其他都是空闲状态。所以这是一个Keras使用多显卡的误区,它并不能同时利用多个GPU。

  1. 目的
    为什么要同时用多个GPU来训练?

单个显卡内存太小 -> batch size无法设的比较大,有时甚至batch_size=1都内存溢出(OUT OF MEMORY)

从我跑深度网络的经验来看,batch_size设的大一点会比较好,相当于每次反向传播更新权重,网络都可以看到更多的样本,从而不会每次iteration都过拟合到不同的地方去Don’t Decay the Learning Rate, Increase the Batch Size。当然,我也看过有论文说也不能设的过大,原因不明… 反正我也没有机会试过。我建议的batch_size大概就是64~256的范围内,都没什么大问题。

但是随着现在网络的深度越来越深,对于GPU的内存要求也越来越大,很多入门的新人最大的问题往往不是代码,而是从Github里面抄下来的代码自己的GPU太渣,实现不了,只能降低batch_size,最后训练不出那种效果。

解决方案两个:
一是买一个超级牛逼的GPU,内存巨大无比;
二是买多个一般般的GPU,一起用。

第一个方案不行,因为目前即便最好的NVIDIA显卡,内存也不过十几个G了不起了,网络一深也挂,并且买一个牛逼显卡的性价比不高。所以、学会在Keras下用多个GPU是比较靠谱的选择。

  1. 实现
    非常简洁
from model import unet
G = 3 # 同时使用3个GPU
with tf.device("/gpu:0"):
        M = unet(input_rows, input_cols, 1)
model = keras.utils.training_utils.multi_gpu_model(M, gpus=G)
model.compile(optimizer=Adam(lr=1e-5), loss='binary_crossentropy', metrics = ['accuracy'])

model.fit(X_train, y_train,
              batch_size=batch_size*G, epochs=nb_epoch, verbose=0, shuffle=True,
              validation_data=(X_valid, y_valid))

model.save_weights('/path/to/save/model.h5')
  1. 问题
    3.1 Compile the model
    如果是普通的网络结构,那么没有问题,像上述的编译代码即可(model.compile(optimizer=Adam(lr=1e-5), loss=’binary_crossentropy’, metrics = [‘accuracy’])) 。不过,如果是Multi-task的网络,例如Faster-RCNN,它由多个输出支路,也就是多个loss,在网络定义的时候一般会给命名,然后编译的时候找到不同支路layer的名字即可,就像这样:
model.compile(optimizer=optimizer, 
              loss={'main_output': jaccard_distance_loss, 'aux_output': 'binary_crossentropy'},
              metrics={'main_output': jaccard_distance_loss, 'aux_output': 'acc'},
              loss_weights={'main_output': 1., 'aux_output': 0.5})

其中main_output和aux_output就是认为定义的layer name,但是如果用了keras.utils.training_utils.multi_gpu_model()以后,名字就自动换掉了,变成默认的concatenate_1, concatenate_2等等,因此你需要先model.summary()一下,打印出来网络结构,然后弄明白哪个输出代表哪个支路,然后重新编译网络,如下:

from keras.optimizers import Adam, RMSprop, SGD
model.compile(optimizer=RMSprop(lr=0.045, rho=0.9, epsilon=1.0), 
              loss={'concatenate_1': jaccard_distance_loss, 'concatenate_2': 'binary_crossentropy'},
              metrics={'concatenate_1': jaccard_distance_loss, 'concatenate_2': 'acc'},
              loss_weights={'concatenate_1': 1., 'concatenate_2': 0.5})

3.2 Save the model
用多个GPU训练的模型有一个问题Keras没有解决,就是model.save()保存的时候报错

TypeError: can’t pickle module objects

或是

RuntimeError: Unable to create attribute (object header message is too large)

原因是
In https://keras.io/utils/#multi_gpu_model it clearly stated that the model can be used like the normal model, but it cannot be saved, very funny. I can’t even perform reinforced training just because I cannot save the previous model trained with multiple GPUs. If trained with single GPU, the rest of my invested GPUs will become useless. Please urge the developer to look into this bug ASAP.

正常情况下Keras给你提供了自动保存最好的网络的函数(keras.callbacks.ModelCheckpoint()),它的内部是用model.save()来保存的,所以不能用了,你需要自己设计函数CustomModelCheckpoint()来保存最好的模型


class CustomModelCheckpoint(keras.callbacks.Callback):

    def __init__(self, model, path):
        self.model = model
        self.path = path
        self.best_loss = np.inf

    def on_epoch_end(self, epoch, logs=None):
        val_loss = logs['val_loss']
        if val_loss < self.best_loss:
            print("\nValidation loss decreased from {} to {}, saving model".format(self.best_loss, val_loss))
            self.model.save_weights(self.path, overwrite=True)
            self.best_loss = val_loss

model.fit(X_train, y_train,
              batch_size=batch_size*G, epochs=nb_epoch, verbose=0, shuffle=True,
              validation_data=(X_valid, y_valid),
              callbacks=[CustomModelCheckpoint(model, '/path/to/save/model.h5')])

即便如此,要是模型还是太大,就需要下面的方法了,保存成npy格式而不是hdf5格式。

RuntimeError: Unable to create attribute (Object header message is too large)

model.get_weights(): returns a list of all weight tensors in the model, as Numpy arrays.
model.set_weights(weights): sets the values of the weights of the model, from a list of Numpy arrays. The arrays in the list should have the same shape as those returned by get_weights().

save model

weight = self.model.get_weights()
np.save(self.path+'.npy', weight)

load model

weight = np.load(load_path)
model.set_weights(weight)

3.3 Load the model
同样道理,当读入用多个显卡一起训练的网络文件.h的时候,也会报错

ValueError: You are trying to load a weight file containing 3 layers into a model with 1 layers.

原因是.h内部和单个GPU训练的存储不太一样,因此在读的时候也需要套一下keras.utils.training_utils.multi_gpu_model()这个函数。

from model import unet
with tf.device("/cpu:0"):
    M = unet(input_rows, input_cols, 1)
model = keras.utils.training_utils.multi_gpu_model(M, gpus=G)
model.load_weights(load_path)

然后就没问题啦。

作者:MrGiovanni
链接:https://www.jianshu.com/p/db0ba022936f
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

当然还有个问题,那就是你使用多模型预测的时候,你可不能注释掉

with tf.device("/cpu:0"):
    M = unet(input_rows, input_cols, 1)

此外,你会发现多GPU模型预测的时候,会比正常的时候慢很多很多,
想知道为什么吗?

其实我也想知道! 谁知道告诉我好不好。

猜你喜欢

转载自blog.csdn.net/MachineRandy/article/details/80040765