tensorflow 确认TF2在训练时使用我的GPU

r1wp621o  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(117)

我想知道是否有一种方法可以确认我的TF模型在我的GPU上训练后,我按照TF教程中的建议将训练数据存储在GPU上。下面是一个简短的代码示例:

import tensorflow as tf

print('Num GPUs Available:', len(tf.config.experimental.list_physical_devices('GPU')))

# load data on GPU
with tf.device('/GPU:0'):
    mnist = tf.keras.datasets.mnist
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    x_train, x_test = x_train / 255.0, x_test / 255.0
# define, compile and train the model
model = tf.keras.models.Sequential([tf.keras.layers.Dense(1)])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['acc'])
model.fit(x_train, y_train, batch_size=32, epochs=5)
cetgtptt

cetgtptt1#

在Tensorflow 2.x中有几种检查GPU的方法。本质上,如果GPU可用,那么模型将在其上运行(除非它被另一个TF示例锁定而处于忙碌状态)。放置也将在日志文件中看到,并且可以使用例如nvidia-smi进行确认。
在下面的代码中,我将假设tensorflow被导入为tf(根据约定和您的代码)。

要检查哪些设备可用,请运行:

tf.config.experimental.list_physical_devices()

下面是我的输出:
【PhysicalDevice(name='/physical_device:CPU:0 ',device_type='CPU'),PhysicalDevice(name='/physical_device:XLA_CPU:0 ',device_type='XLA_CPU'),PhysicalDevice(name='/physical_device:GPU:0 ',device_type='GPU'),PhysicalDevice(name='/physical_device:XLA_GPU:0 ',device_type='XLA_GPU')】
为了检查系统上是否有GPU:

is_gpu = len(tf.config.experimental.list_physical_devices('GPU')) > 0

从Tensorflow 2.1开始,此功能已从实验迁移,您可以以相同的方式使用:用途:tf.config.list_physical_devices(),即

is_gpu = len(tf.config.list_physical_devices('GPU')) > 0

在某个时间点,实验部分将被弃用。
最后但并非最不重要的是,如果你的tensorflow是在没有CUDA的情况下构建的(它是一个非GPU版本),list_physical_devices('GPU')也将返回False,即使你的系统物理上有一个GPU。

“GPU被TF识别后是否自动?”

是的。在TF docs之后引用:
注意:使用tf.config.experimental.list_physical_devices('GPU')确认TensorFlow正在使用GPU。
如果它被识别,它将在训练过程中使用。如果你想完全确定,你可以要求更明确的日志记录:

tf.debugging.set_log_device_placement(True)
svmlkihl

svmlkihl2#

有一个更简单的方法来实现这一点:

import tensorflow as tf
if tf.test.gpu_device_name():
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
else:
    print(""Please install GPU version of TF"")

(或)

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

(或)
TF中出现了一些有用的功能:
告诉gpu是否可用

tf.test.is_gpu_available()

返回GPU设备的名称”

tf.test.gpu_device_name()
kuarbcqp

kuarbcqp3#

现在在8月23日这里--使用这个tf.config.list_physical_devices('GPU')源代码官方TF安装页面。tensorflow.org/install/pip

相关问题