0

我正在尝试创建一个非常大的 Keras 模型并将其分布在多个 GPU 上。需要明确的是,我并不是想将同一模型的多个副本放在多个 GPU 上。我正在尝试将一个大型模型放在多个 GPU 上。我一直在 Ke​​ras 中使用 multi_gpu_model 函数,但是基于我在执行此操作时遇到的许多内存不足错误,它似乎只是在复制模型而不是像我想要的那样分发它。

我查看了 Horovod,但因为我有很多特定于 Windows 的日志记录工具正在运行,所以我对使用它犹豫不决。

这似乎只留下 tf.estimators 供我使用。尽管我将如何使用这些估计器来做我想做的事情,但从文档中并不清楚。例如,tf.contrib.distribute 中的哪种分配策略可以让我以我想要的方式有效地批量处理模型?

我正在寻求对估算器做什么,如果可以,我应该使用哪种策略?

4

3 回答 3

1

您可以使用 Estimator API。使用转换您的模型tf.keras.estimator.model_to_estimator

session_config = tf.ConfigProto(allow_soft_placement=True)
distribute = tf.contrib.distribute.MirroredStrategy(num_gpus=4)
run_config = tf.estimator.RunConfig(train_distribute=distribute)
your_network = tf.keras.estimator.model_to_estimator(model_fn=your_keras_model, config=run_config)
your_network.train(input_fn)

不要忘记编译模型

于 2019-02-05T18:18:27.247 回答
0

您可以使用 TensorFlow 后端手动将 Keras 模型的不同部分分配给不同的 GPU。本指南提供了详细的示例,本文解释了如何将 Keras 与 TensorFlow 结合使用。

import tensorflow as tf

with tf.device("/device:GPU:0"):
    #Create first part of your neural network

with tf.device("/device:GPU:1"):
    #Create second part of your neural network

#...

with tf.device("/device:GPU:n"):
    #Create nth part of your neural network

注意:CPU 和多个 GPU 之间的通信延迟可能会增加训练的大量开销。

于 2019-02-05T18:08:19.877 回答
0

您需要设备并行性。Keras FAQ 的这一部分提供了如何使用 Keras 执行此操作的示例:

# 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)
于 2019-02-05T19:41:59.667 回答