当前位置: 移动技术网 > IT编程>脚本编程>Python > keras 多gpu并行运行案例

keras 多gpu并行运行案例

2020年06月18日  | 移动技术网IT编程  | 我要评论

孤岛飞鹰鸽子是谁,中国营销论坛,pba化妆品怎么样

一、多张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.h5')

注意:

要保存多 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并行运行案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网