【发布时间】:2021-09-17 20:25:55
【问题描述】:
当使用多个 GPU 对模型执行推理(例如调用方法:model(inputs))并计算其梯度时,机器只使用一个 GPU,其余的空闲。
例如下面这段代码sn-p:
import tensorflow as tf
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
# Make the tf-data
path_filename_records = 'your_path_to_records'
bs = 128
dataset = tf.data.TFRecordDataset(path_filename_records)
dataset = (dataset
.map(parse_record, num_parallel_calls=tf.data.experimental.AUTOTUNE)
.batch(bs)
.prefetch(tf.data.experimental.AUTOTUNE)
)
# Load model trained using MirroredStrategy
path_to_resnet = 'your_path_to_resnet'
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
resnet50 = tf.keras.models.load_model(path_to_resnet)
for pre_images, true_label in dataset:
with tf.GradientTape() as tape:
tape.watch(pre_images)
outputs = resnet50(pre_images)
grads = tape.gradient(outputs, pre_images)
仅使用一个 GPU。您可以使用 nvidia-smi 分析 GPU 的行为。我不知道它是否应该是这样的,model(inputs) 和tape.gradient 都没有多 GPU 支持。但如果是这样,那么这是一个大问题,因为如果你有一个大数据集并且需要计算关于输入的梯度(例如可解释性语料库),使用一个 GPU 可能需要几天时间。
我尝试的另一件事是使用model.predict(),但使用tf.GradientTape 是不可能的。
到目前为止我已经尝试过但没有成功
- 将所有代码放入镜像策略范围内。
- 使用不同的 GPU:我尝试过 A100、A6000 和 RTX5000。还更改了显卡数量并改变了批量大小。
- 指定了 GPU 列表,例如,
strategy = tf.distribute.MirroredStrategy(['/gpu:0', '/gpu:1'])。 - 按照@Kaveh 的建议添加了这个
strategy = tf.distribute.MirroredStrategy(cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())。
我怎么知道只有一个 GPU 在工作?
我在终端使用命令watch -n 1 nvidia-smi,观察到只有一个GPU处于100%,其余处于0%。
工作示例
您可以在下面的 dogs_vs_cats 数据集上找到一个使用 CNN 训练的工作示例。你不需要手动下载数据集,因为我使用的是 tfds 版本,也不需要训练模型。
保存的模型:
【问题讨论】:
-
您可能需要将所有代码放在镜像策略范围内,现在只有模型加载在范围内。
-
如何确定正在使用一个 GPU?
-
这个
strategy = tf.distribute.MirroredStrategy(cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())可能会解决您的问题。 -
你试过在你的定义中列出 gpus 吗?像这样:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]). -
您能提供一个最小的可重现示例吗?现在,在尝试重现该行为时,我使用了 2 个 GPU。在任何情况下,您可能想查看:tensorflow.org/api_docs/python/tf/distribute/…
标签: tensorflow keras multi-gpu