【问题标题】:Best practice for allocating GPU and CPU resources in TensorFlow在 TensorFlow 中分配 GPU 和 CPU 资源的最佳实践
【发布时间】:2020-03-23 06:32:49
【问题描述】:

我想知道设置设备以创建/训练模型以优化资源使用以使用 Keras API 在 TensorFlow 中进行快速训练的正确方法是什么?我有 1 个 CPU 和 2 个 GPU 可供使用。我最初使用 tf.device 上下文来创建我的模型并仅在 GPU 上训练,但后来我在 TensorFlow 文档中看到 tf.keras.utils.multi_gpu_model,他们建议在 CPU 上显式实例化模型:

# Instantiate the base model (or "template" model).
# We recommend doing this with under a CPU device scope,
# so that the model's weights are hosted on CPU memory.
# Otherwise they may end up hosted on a GPU, which would
# complicate weight sharing.
with tf.device('/cpu:0'):
    model = Xception(weights=None,
                     input_shape=(height, width, 3),
                     classes=num_classes)

# Replicates the model on 8 GPUs.
# This assumes that your machine has 8 available GPUs.
parallel_model = multi_gpu_model(model, gpus=8)
parallel_model.compile(loss='categorical_crossentropy',
                       optimizer='rmsprop')

我这样做了,现在当我训练时,我发现我的 CPU 使用率大幅上升,所有 8 个内核的使用率都达到了大约 70%,并且我的 GPU 内存已达到最大值。如果模型是在其中一个 GPU 上创建的,事情会变得更快吗?即使我只有 1 个 GPU,在 CPU 上创建模型并使用 tf.device 上下文在 GPU 上训练模型是否更好?

【问题讨论】:

    标签: python tensorflow gpu cpu tf.keras


    【解决方案1】:

    许多 TensorFlow 操作都使用 GPU 进行加速计算。在没有任何注释的情况下,TensorFlow 会自动决定是使用 GPU 还是 CPU 进行操作——如有必要,在 CPU 和 GPU 内存之间复制张量。操作产生的张量通常由执行操作的设备的内存支持。

    Tensorflow 只会在可见的物理设备上分配内存和放置操作,否则不会在它们上创建 LogicalDevice。默认情况下,所有发现的设备都标记为可见。

    GPU 利用率也取决于batch_size。利用率可能会随着 batch_size 的变化而变化。

    您还可以使用来自multi_gpu_modelExample 3 将您当前的结果(所用时间和利用率)与模型进行比较。

    此外,如果您进入链接,它会声明 -

    警告:此功能已弃用。它将在 2020-04-01 之后删除。更新说明:改用 tf.distribute.MirroredStrategy。

    使用tf.distribute.MirroredStrategy 应该可以提高性能和 GPU 利用率。此策略通常用于在具有多个 GPU 的一台机器上进行训练。 tf.distribute.Strategy API 提供了一种抽象,用于将您的训练分布在多个处理单元中。目标是允许用户使用现有模型和训练代码启用分布式训练,只需进行最少的更改。

    例如,在MirroredStrategy 下创建的变量是MirroredVariable。如果在策略的构造函数参数中没有指定设备,那么它将使用所有可用的GPUs。如果没有找到GPUs,它将使用可用的CPUs。请注意,TensorFlow 将机器上的所有 CPUs 视为单个设备,并在内部使用线程进行并行处理。

    建议阅读 Custom training with tf.distribute.Strategy 教程,该教程演示了如何将 tf.distribute.Strategy 与自定义训练循环一起使用。他们将在时尚 MNIST 数据集上训练一个简单的 CNN 模型。

    希望这能回答您的问题。快乐学习。

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 2017-08-11
      • 2023-03-23
      • 2015-11-18
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2010-12-24
      • 2020-04-30
      相关资源
      最近更新 更多