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

How to tell if tensorflow is using gpu acceleration from inside python shell?

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

现在我的问题是如何测试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?

不,我认为“打开 CUDA 库”不足以说明问题,因为图形的不同节点可能位于不同的设备上。

使用tensorflow2时:

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

对于tensorflow1,要找出使用的是哪个设备,您可以像这样启用日志设备放置:

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

检查您的控制台是否有此类输出。

这将确认 tensorflow 在训练时也使用 GPU?

代码

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

输出

I tensorflow/core/common_runtime/gpu/gpu_device.cc:885] Found device 0 with properties: 
name: GeForce GT 730
major: 3 minor: 5 memoryClockRate (GHz) 0.9015
pciBusID 0000:01:00.0
Total memory: 1.98GiB
Free memory: 1.72GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0
I tensorflow/core/common_runtime/direct_session.cc:255] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GT 730, pci bus id: 0000:01:00.0

除了使用其他答案和官方TensorFlow documentation中概述的sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))外,您可以尝试将计算分配给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并且可以使用它,你会看到结果。否则你会看到一个长堆栈跟踪的错误。最后你会得到这样的东西:

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 会 return 你会像

[_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)

我更喜欢使用 nvidia-smi 来监控 GPU 使用情况。如果当你开始编程时它显着上升,这是一个强烈的迹象,表明你的 tensorflow 正在使用 GPU。

运行 Jupyter 中的以下内容,

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

如果您已正确设置环境,您将在 运行 "jupyter notebook",

2017-10-05 14:51:46.335323: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro K620, pci bus id: 0000:02:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro K620, pci bus id: 0000:02:00.0
2017-10-05 14:51:46.337418: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\tensorflow\core\common_runtime\direct_session.cc:265] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro K620, pci bus id: 0000:02:00.0

你可以在这里看到我在 Nvidia Quodro K620 上使用 TensorFlow。

这应该给出可用于 Tensorflow 的设备列表(在 Py-3.6 下):

tf = tf.Session(config=tf.ConfigProto(log_device_placement=True))
tf.list_devices()
# _DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456)

我发现从命令行查询 gpu 是最简单的:

nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.98                 Driver Version: 384.98                    |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 980 Ti  Off  | 00000000:02:00.0  On |                  N/A |
| 22%   33C    P8    13W / 250W |   5817MiB /  6075MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1060      G   /usr/lib/xorg/Xorg                            53MiB |
|    0     25177      C   python                                      5751MiB |
+-----------------------------------------------------------------------------+

如果您的学习是后台进程,则 pid 来自 jobs -p 应该匹配来自 nvidia-smi

的 pid

下面的一段代码应该给你所有可用于 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" ]

我认为有一种更简单的方法可以实现这一点。

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")

通常打印成

Default GPU Device: /device:GPU:0

这对我来说似乎比那些冗长的日志更容易。

编辑:- 这已针对 TF 1.x 版本进行了测试。我从来没有机会用 TF 2.0 或更高版本做事所以请记住。

好的,首先从终端启动 ipython shellimport TensorFlow:

$ ipython --pylab
Python 3.6.5 |Anaconda custom (64-bit)| (default, Apr 29 2018, 16:14:56) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
Using matplotlib backend: Qt5Agg

In [1]: import tensorflow as tf

现在,我们可以使用以下命令在控制台中观察 GPU 内存使用情况:

# realtime update for every 2s
$ watch -n 2 nvidia-smi

因为我们只 imported TensorFlow 但还没有使用任何 GPU,所以使用统计数据将是:

注意 GPU 内存使用量非常少 (~ 700MB);有时 GPU 内存使用量甚至可能低至 0 MB。


现在,让我们在代码中加载 GPU。如 tf documentation 所示,执行:

In [2]: sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

现在,watch 统计数据应该显示更新后的 GPU 使用内存,如下所示:

现在观察来自 ipython shell 的 Python 进程如何使用 ~ 7 GB 的 GPU 内存。


P.S。您可以继续 观看 这些统计数据,因为代码是 运行,以了解 GPU 使用率随时间推移的强度。

除了其他答案之外,以下内容应该可以帮助您确保您的 tensorflow 版本包括 GPU 支持。

import tensorflow as tf
print(tf.test.is_built_with_cuda())

您可以通过运行以下代码检查您当前是否正在使用GPU:

import tensorflow as tf
tf.test.gpu_device_name()

如果输出为'',则表示您只使用了CPU
如果输出类似于 /device:GPU:0,则表示 GPU 有效。


并使用以下代码检查您使用的 GPU

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

张量流 2.0

会话在 2.0 中不再使用。相反,可以使用 tf.test.is_gpu_available:

import tensorflow as tf

assert tf.test.is_gpu_available()
assert tf.test.is_built_with_cuda()

如果出现错误,您需要检查安装。

将它放在你的 jupyter notebook 的顶部附近。把不需要的注释掉。

# confirm TensorFlow sees the GPU
from tensorflow.python.client import device_lib
assert 'GPU' in str(device_lib.list_local_devices())

# confirm Keras sees the GPU (for TensorFlow 1.X + Keras)
from keras import backend
assert len(backend.tensorflow_backend._get_available_gpus()) > 0

# confirm PyTorch sees the GPU
from torch import cuda
assert cuda.is_available()
assert cuda.device_count() > 0
print(cuda.get_device_name(cuda.current_device()))

注意:随着 TensorFlow 2.0 的发布,Keras 现已作为 TF 的一部分包含在内API。

最初回答

最近更新了Tensorflow,您可以通过以下方式查看:

tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None)

如果 Tensorflow 使用 GPU,这将 return True,否则 return False

如果您想要设备 device_name,您可以输入:tf.test.gpu_device_name()。 从 here

获取更多详细信息

这是我用来直接从 bash 列出 tf.session 可用设备的行:

python -c "import os; os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'; import tensorflow as tf; sess = tf.Session(); [print(x) for x in sess.list_devices()]; print(tf.__version__);"

它将打印可用的设备和tensorflow版本,例如:

_DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 10588614393916958794)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 12320120782636586575)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 13378821206986992411)
_DeviceAttributes(/job:localhost/replica:0/task:0/device:GPU:0, GPU, 32039954023, 12481654498215526877)
1.14.0

您有一些选项可以测试您的 TensorFlow 安装是否正在使用 GPU 加速。

您可以在三个不同的平台上输入以下命令。

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
  1. Jupyter Notebook - 检查 运行 Jupyter Notebook 的控制台。您将能够看到正在使用的 GPU。
  2. Python Shell - 您将能够直接看到输出。 (注意 - 不要将第二个命令的输出分配给变量 'sess';如果有帮助的话)。
  3. Spyder - 在控制台中输入以下命令。

    import tensorflow as tf tf.test.is_gpu_available()

以下还将return您的 GPU 设备的名称。

import tensorflow as tf
tf.test.gpu_device_name()

我发现下面的代码片段非常方便测试 gpu ..

Tensorflow 2.0 测试

import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
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))

Tensorflow 1 测试

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))

如果您使用的是 TensorFlow 2.0,则可以使用此 for 循环来显示设备:

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

如果您使用的是 tensorflow 2.x 使用:

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

对于 Tensorflow 2.0

import tensorflow as tf

tf.test.is_gpu_available(
    cuda_only=False,
    min_cuda_compute_capability=None
)

来源here

其他选项是:

tf.config.experimental.list_physical_devices('GPU')

运行 在 Jupyter 或您的 IDE 中使用此命令检查 Tensorflow 是否正在使用 GPU:tf.config.list_physical_devices('GPU')

TensorFlow 更新 >= 2.1.

检查 TensorFlow 是否使用 GPU 的推荐方法如下:

tf.config.list_physical_devices('GPU') 

从 TensorFlow 2.1 开始,tf.test.gpu_device_name() 已被弃用,取而代之的是上述内容。

然后,您可以在终端中使用 nvidia-smi 检查分配了多少 GPU 显存;同时,使用 watch -n K nvidia-smi 会告诉你例如每 K 秒你使用了多少内存(你可能想实时使用 K = 1

如果您有多个 GPU 并且想要使用多个网络,每个网络都在一个单独的 GPU 上,您可以使用:

 with tf.device('/GPU:0'):
      neural_network_1 = initialize_network_1()
 with tf.device('/GPU:1'):
      neural_network_2 = initialize_network_2()

使用 tensorflow 2.0 >=

import tensorflow as tf
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

张量流 2.1

一个简单的计算,可以用 nvidia-smi 验证 GPU 上的内存使用情况。

import tensorflow as tf 

c1 = []
n = 10

def matpow(M, n):
    if n < 1: #Abstract cases where n < 1
        return M
    else:
        return tf.matmul(M, matpow(M, n-1))

with tf.device('/gpu:0'):
    a = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="a")
    b = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="b")
    c1.append(matpow(a, n))
    c1.append(matpow(b, n))
>>> import tensorflow as tf 
>>> tf.config.list_physical_devices('GPU')

2020-05-10 14:58:16.243814: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2020-05-10 14:58:16.262675: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.263119: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1060 6GB computeCapability: 6.1
coreClock: 1.7715GHz coreCount: 10 deviceMemorySize: 5.93GiB deviceMemoryBandwidth: 178.99GiB/s
2020-05-10 14:58:16.263143: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-05-10 14:58:16.263188: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-05-10 14:58:16.264289: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10
2020-05-10 14:58:16.264495: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10
2020-05-10 14:58:16.265644: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10
2020-05-10 14:58:16.266329: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10
2020-05-10 14:58:16.266357: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-05-10 14:58:16.266478: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.266823: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.267107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

根据@AmitaiIrron 的建议:

此部分表示已找到 gpu

2020-05-10 14:58:16.263119: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:

pciBusID: 0000:01:00.0 name: GeForce GTX 1060 6GB computeCapability: 6.1
coreClock: 1.7715GHz coreCount: 10 deviceMemorySize: 5.93GiB deviceMemoryBandwidth: 178.99GiB/s

在这里它被添加为可用的物理设备

2020-05-10 14:58:16.267107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0

[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

对于在 tensorflow website 上列为“官方”方式的 TF2.4+,以检查 TF 是否正在使用 GPU

>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Num GPUs Available:  2

在新版本的TF(>2.1)中,推荐的检查TF是否使用GPU的方法是:

tf.config.list_physical_devices('GPU')

我找到了最简单全面的方法。只需设置 tf.debugging.set_log_device_placement(True),您应该会看到操作在 GPU 上是否实际上是 运行,例如Executing op _EagerConst in device /job:localhost/replica:0/task:0/device:GPU:0

文档中有更多内容:https://www.tensorflow.org/guide/gpu#logging_device_placement

也许试试这个:

python -c "将 tensorflow 导入为 tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))"

看系统returns张量

根据the site