gpt4 book ai didi

tensorflow - Keras 中的数据并行性

转载 作者:行者123 更新时间:2023-12-03 16:27:41 33 4
gpt4 key购买 nike

我正在寻找 keras(tensorflow 后端)中的数据并行性,而不是模型并行性。
我正在对视频文件执行视频分类,因此在 GPU 中只能容纳一批大小为 2 的文件。所以,我想知道一种使用多个 GPU 的方法来增加我的批量大小,以便更好地估计和更快地训练。
你能建议我一个有效的方法来做到这一点吗?

我正在使用一个 12gb TitanX 和一个 6gb Titan Black。

谢谢

最佳答案

这是一种方法:

此方法to_multi_gpu得到一个 model (在单个 GPU 上使用 Keras 2.0 定义),并返回在多个 GPU 上复制(使用共享参数)的相同模型。新模型的输入被均匀切片,每个切片都传递给复制模型之一。所有复制模型的输出最后连接在一起。

from keras import backend as K
from keras.models import Model
from keras.layers import Input
from keras.layers.core import Lambda
from keras.layers.merge import Concatenate

def slice_batch(x, n_gpus, part):
"""
Divide the input batch into [n_gpus] slices, and obtain slice number [part].
i.e. if len(x)=10, then slice_batch(x, 2, 1) will return x[5:].
"""
sh = K.shape(x)
L = sh[0] // n_gpus
if part == n_gpus - 1:
return x[part*L:]
return x[part*L:(part+1)*L]


def to_multi_gpu(model, n_gpus=2):
"""
Given a keras [model], return an equivalent model which parallelizes
the computation over [n_gpus] GPUs.

Each GPU gets a slice of the input batch, applies the model on that slice
and later the outputs of the models are concatenated to a single tensor,
hence the user sees a model that behaves the same as the original.
"""
with tf.device('/cpu:0'):
x = Input(model.input_shape[1:], name=model.input_names[0])

towers = []
for g in range(n_gpus):
with tf.device('/gpu:' + str(g)):
slice_g = Lambda(slice_batch,
lambda shape: shape,
arguments={'n_gpus':n_gpus, 'part':g})(x)
towers.append(model(slice_g))

with tf.device('/cpu:0'):
merged = Concatenate(axis=0)(towers)

return Model(inputs=[x], outputs=[merged])

关于tensorflow - Keras 中的数据并行性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821786/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com