如何判断tensorflow是否在使用python shell内部的gpu加速?

2024-04-19 20:30:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在我的ubuntu 16.04中安装了tensorflow,使用的是ubuntu内置apt cuda安装的第二个答案here

现在我的问题是如何测试tensorflow是否真的在使用gpu?我有一台gtx 960m gpu。当我import tensorflow这是输出

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally

这个输出是否足以检查tensorflow是否正在使用gpu?


Tags: streamsogpuubuntutensorflowlibraryloader内置
3条回答

除了使用sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))(在其他答案中以及在官方的TensorFlowdocumentation中概述)之外,您还可以尝试将计算分配给gpu并查看是否有错误。

import tensorflow as tf
with tf.device('/gpu:0'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    c = tf.matmul(a, b)

with tf.Session() as sess:
    print (sess.run(c))

这里

  • “/cpu:0”:您机器的cpu。
  • “/gpu:0”:机器的gpu,如果有的话。

如果你有一个gpu并且可以使用它,你会看到结果。否则您将看到长stacktrace的错误。最后你会得到这样的东西:

Cannot assign a device to node 'MatMul': Could not satisfy explicit device specification '/device:GPU:0' because no devices matching that specification are registered in this process


最近在TF中出现了一些有用的功能:

您还可以检查会话中的可用设备:

with tf.Session() as sess:
  devices = sess.list_devices()

devices将返回如下内容

[_DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:CPU:0, CPU, -1, 4670268618893924978),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 6127825144471676437),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 16148453971365832732),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:TPU:0, TPU, 17179869184, 10003582050679337480),
 _DeviceAttributes(/job:tpu_worker/replica:0/task:0/device:TPU:1, TPU, 17179869184, 5678397037036584928)

下面的代码将为您提供tensorflow可用的所有设备。

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Sample Output

[name: "/cpu:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 4402277519343584096,

name: "/gpu:0" device_type: "GPU" memory_limit: 6772842168 locality { bus_id: 1 } incarnation: 7471795903849088328 physical_device_desc: "device: 0, name: GeForce GTX 1070, pci bus id: 0000:05:00.0" ]

不,我认为“open CUDA library”不足以说明问题,因为图中的不同节点可能在不同的设备上。

要查找使用的设备,可以启用日志设备放置,如下所示:

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

检查您的控制台是否有这种类型的输出。

相关问题 更多 >