我已经使用第二个答案 here 和 ubuntu 的内置 apt cuda 安装在我的 ubuntu 16.04 中安装了 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 ?
log_device_placement
的回答方法。最可靠的方法是查看此评论中指定的时间线:github.com/tensorflow/tensorflow/issues/…
tf.config.list_physical_devices('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))
检查您的控制台以获取此类输出。
https://i.stack.imgur.com/RtRiB.png
除了使用其他答案以及官方 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 并且可以使用它,你会看到结果。否则,您将看到带有长堆栈跟踪的错误。最后你会得到这样的东西:
无法将设备分配给节点“MatMul”:无法满足明确的设备规范“/device:GPU:0”,因为在此过程中没有注册符合该规范的设备
最近 TF 中出现了一些有用的功能:
tf.test.is_gpu_available 告诉 gpu 是否可用
tf.test.gpu_device_name 返回 gpu 设备的名称
您还可以检查会话中的可用设备:
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)
Session
替换为 tf.compat.v1.Session()
以下代码应该为您提供可用于 tensorflow 的所有设备。
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
示例输出 [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:“设备:0,名称:GeForce GTX 1070,pci 总线 ID:0000:05:00.0”]
张量流 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()
如果出现错误,则需要检查您的安装。
tf.config.list_physical_devices('GPU')
我认为有一种更简单的方法可以实现这一目标。
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 shell
和 import
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
由于我们仅import
使用了 TensorFlow,但尚未使用任何 GPU,因此使用情况统计数据为:
https://i.stack.imgur.com/8sCM1.png
请注意 GPU 内存使用量非常少(~ 700MB);有时 GPU 内存使用量甚至可能低至 0 MB。
现在,让我们在代码中加载 GPU。如 tf documentation
所示,执行以下操作:
In [2]: sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
现在,watch stats 应该显示更新的 GPU 使用内存,如下所示:
https://i.stack.imgur.com/PlUji.png
现在观察 ipython shell 中的 Python 进程如何使用约 7 GB 的 GPU 内存。
PS 您可以在代码运行时继续观察这些统计数据,以了解 GPU 使用量随时间的变化情况。
这将确认 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
log_device_placement
做什么以及如何在输出中查看 CPU 与 GPU?)添加一点解释。这将提高您的答案的质量!
除了其他答案之外,以下内容应该可以帮助您确保您的 tensorflow 版本包含 GPU 支持。
import tensorflow as tf
print(tf.test.is_built_with_cuda())
更新 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()
nvidia-smi -l 10
。
这应该给出可用于 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)
我更喜欢使用 nvidia-smi 来监控 GPU 使用情况。如果在您开始编程时它显着上升,则表明您的 tensorflow 正在使用 GPU。
使用 Tensorflow 的最新更新,您可以按如下方式进行检查:
tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None)
如果 Tensorflow
正在使用 GPU,这将返回 True
,否则返回 False
。
如果您想要设备 device_name
,您可以输入:tf.test.gpu_device_name()
。从 here 获取更多详细信息
使用张量流 2.0 >=
import tensorflow as tf
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))
https://i.stack.imgur.com/VEWI0.png
在 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\35\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\35\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
你可以在这里看到我正在使用 TensorFlow 和 Nvidia Quodro K620。
我发现从命令行查询 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 |
+-----------------------------------------------------------------------------+
如果您的学习是后台进程,来自 jobs -p
的 pid 应该与来自 nvidia-smi
的 pid 匹配
您可以通过运行以下代码来检查您当前是否正在使用 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()
' '
,那我们该怎么办?
把它放在你的 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 的一部分包含在内。
最初回答了 here。
>>> 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')]
正如@AmitaIrron 所建议的:
此部分表示找到了一个 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')]
我发现下面的代码片段非常方便测试 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
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')
is_gpu_available
(来自 tensorflow.python.framework.test_util)已弃用,将在未来版本中删除。
以下还将返回您的 GPU 设备的名称。
import tensorflow as tf
tf.test.gpu_device_name()
在新版本的 TF(>2.1) 中,检查 TF 是否使用 GPU 的推荐方法是:
tf.config.list_physical_devices('GPU')
在 Jupyter 或您的 IDE 中运行此命令以检查 Tensorflow 是否使用 GPU:tf.config.list_physical_devices('GPU')
张量流 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))
对于 TensorFlow 网站上列为“官方”方式的 TF2.4+ 来检查 TF 是否使用 GPU
>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Num GPUs Available: 2
这是我用来直接从 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))
Jupyter Notebook - 检查运行 Jupyter Notebook 的控制台。您将能够看到正在使用的 GPU。 Python Shell - 您将能够直接看到输出。 (注意 - 不要将第二个命令的输出分配给变量 'sess';如果有帮助的话)。 Spyder - 在控制台中输入以下命令。将张量流导入为 tf tf.test.is_gpu_available()
如果你使用的是 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))
我找到了最简单、最全面的方法。只需设置 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
不定期副业成功案例分享
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))