温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

keras如何用多gpu并行运行

发布时间:2020-07-17 10:55:47 来源:亿速云 阅读:435 作者:小猪 栏目:开发技术

这篇文章主要为大家展示了keras如何用多gpu并行运行,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

一、多张gpu的卡上使用keras

有多张gpu卡时,推荐使用tensorflow 作为后端。使用多张gpu运行model,可以分为两种情况,一是数据并行,二是设备并行。

二、数据并行

数据并行将目标模型在多个设备上各复制一份,并使用每个设备上的复制品处理整个数据集的不同部分数据。

利用multi_gpu_model实现

keras.utils.multi_gpu_model(model, gpus=None, cpu_merge=True, cpu_relocation=False)

具体来说,该功能实现了单机多 GPU 数据并行性。 它的工作原理如下:

将模型的输入分成多个子批次。

在每个子批次上应用模型副本。 每个模型副本都在专用 GPU 上执行。

将结果(在 CPU 上)连接成一个大批量。

例如, 如果你的 batch_size 是 64,且你使用 gpus=2, 那么我们将把输入分为两个 32 个样本的子批次, 在 1 个 GPU 上处理 1 个子批次,然后返回完整批次的 64 个处理过的样本。

参数

model: 一个 Keras 模型实例。为了避免OOM错误,该模型可以建立在 CPU 上, 详见下面的使用样例。

gpus: 整数 >= 2 或整数列表,创建模型副本的 GPU 数量, 或 GPU ID 的列表。

cpu_merge: 一个布尔值,用于标识是否强制合并 CPU 范围内的模型权重。

cpu_relocation: 一个布尔值,用来确定是否在 CPU 的范围内创建模型的权重。如果模型没有在任何一个设备范围内定义,您仍然可以通过激活这个选项来拯救它。

返回

一个 Keras Model 实例,它可以像初始 model 参数一样使用,但它将工作负载分布在多个 GPU 上。

例子

import tensorflow as tf
from keras.applications import Xception
from keras.utils import multi_gpu_model
import numpy as np

num_samples = 1000
height = 224
width = 224
num_classes = 1000

# 实例化基础模型(或者「模版」模型)。
# 我们推荐在 CPU 设备范围内做此操作,
# 这样模型的权重就会存储在 CPU 内存中。
# 否则它们会存储在 GPU 上,而完全被共享。
with tf.device('/cpu:0'):
 model = Xception(weights=None,
   input_shape=(height, width, 3),
   classes=num_classes)

# 复制模型到 8 个 GPU 上。
# 这假设你的机器有 8 个可用 GPU。
parallel_model = multi_gpu_model(model, gpus=8)
parallel_model.compile(loss='categorical_crossentropy',
   optimizer='rmsprop')

# 生成虚拟数据
x = np.random.random((num_samples, height, width, 3))
y = np.random.random((num_samples, num_classes))

# 这个 `fit` 调用将分布在 8 个 GPU 上。
# 由于 batch size 是 256, 每个 GPU 将处理 32 个样本。
parallel_model.fit(x, y, epochs=20, batch_size=256)

# 通过模版模型存储模型(共享相同权重):
model.save('my_model.h6')

注意:

要保存多 GPU 模型,请通过模板模型(传递给 multi_gpu_model 的参数)调用 .save(fname) 或 .save_weights(fname) 以进行存储,而不是通过 multi_gpu_model 返回的模型。

即要用model来保存,而不是parallel_model来保存。

使用ModelCheckpoint() 遇到的问题

使用ModelCheckpoint()会遇到下面的问题:

TypeError: can't pickle ...(different text at different situation) objects

这个问题和保存问题类似,ModelCheckpoint() 会自动调用parallel_model.save()来保存,而不是model.save(),因此我们要自己写一个召回函数,使得ModelCheckpoint()用model.save()。

修改方法:

class ParallelModelCheckpoint(ModelCheckpoint):
 def __init__(self,model,filepath, monitor='val_loss', verbose=0,
   save_best_only=False, save_weights_only=False,
   mode='auto', period=1):
 self.single_model = model
 super(ParallelModelCheckpoint,self).__init__(filepath, monitor, verbose,save_best_only, save_weights_only,mode, period)

 def set_model(self, model):
 super(ParallelModelCheckpoint,self).set_model(self.single_model)

checkpoint = ParallelModelCheckpoint(original_model)

ParallelModelCheckpoint调用的时候,model应该为原来的model而不是parallel_model。

EarlyStopping 没有此类问题

二、设备并行

设备并行适用于多分支结构,一个分支用一个gpu。

这种并行方法可以通过使用TensorFlow device scopes实现,下面是一个例子:

# Model where a shared LSTM is used to encode two different sequences in parallel
input_a = keras.Input(shape=(140, 256))
input_b = keras.Input(shape=(140, 256))

shared_lstm = keras.layers.LSTM(64)

# Process the first sequence on one GPU
with tf.device_scope('/gpu:0'):
 encoded_a = shared_lstm(tweet_a)
# Process the next sequence on another GPU
with tf.device_scope('/gpu:1'):
 encoded_b = shared_lstm(tweet_b)

# Concatenate results on CPU
with tf.device_scope('/cpu:0'):
 merged_vector = keras.layers.concatenate([encoded_a, encoded_b],
      axis=-1)

三、分布式运行

keras的分布式是利用TensorFlow实现的,要想完成分布式的训练,你需要将Keras注册在连接一个集群的TensorFlow会话上:

server = tf.train.Server.create_local_server()
sess = tf.Session(server.target)

from keras import backend as K
K.set_session(sess)

以上就是关于keras如何用多gpu并行运行的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI