TensorFlow切换CPU/GPU

44

已安装tensorflow GPU(在一台低端的NVIDIA GeForce 950上运行),我希望与CPU性能进行比较。

我正在运行tensorFlow MNIST教程代码,注意到切换到GPU后速度显著提升-—至少是估计上的(两天前我在一台i7笔记本电脑上以批量大小为100运行了CPU版本,而在桌面GPU上运行批量大小为10)—-但我只在将GPU的批处理大小从100降低到10时才发现速度增加...

现在,我缺少客观的衡量标准来评估我所获得的优势。

是否有一种方法在CPU和GPU张量流之间切换?

6个回答

39
使GPU不可见
export CUDA_VISIBLE_DEVICES=""

回归正常

unset CUDA_VISIBLE_DEVICES

9
这放在哪里? - Chaine
2
或者 CUDA_VISIBLE_DEVICES="" python myscript.py - Maksym Ganenko
在终端中输入@Chaine,然后运行你的python my_script.py - Conchylicultor

20

尝试将 tf.device 设置为 cpu:0。

with tf.Session() as sess:
     with tf.device("/cpu:0"):

7

另一种选择是在两个虚拟环境中安装tensorflow的cpu版本和gpu版本,有关如何在虚拟环境中安装tensorflow的详细说明在此处列出https://www.tensorflow.org/get_started/os_setup; 这样,您可以在两个终端窗口中运行相同的代码,一个使用CPU,另一个使用GPU。


6
# Check if the server/ instance is having GPU/ CPU from python code
import sys
import tensorflow as tf
from tensorflow.python.client import device_lib

# device_lib.list_local_devices()     ## this command list all the processing device GPU and CPU


device_name = [x.name for x in device_lib.list_local_devices() if x.device_type == 'GPU']
if device_name[0] == "/device:GPU:0":
    device_name = "/gpu:0"
    #print('GPU')
else:
    #print('CPU')
    device_name = "/cpu:0"

with tf.device(device_name):
    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))    

6

要关闭GPU,只需在您的脚本顶部添加以下内容。

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

(当您想再次使用GPU时,请将其注释掉)


6

相当长的时间过去了。Tensorflow 的最近版本(至少从 2.0 开始)不需要同时安装带有和没有 GPU 支持的版本,因此您可以启动两个单独的 jupyter-notebook 实例。遵循 @Yaroslav 的建议:

$ CUDA_VISIBLE_DEVICES="" jupyter-notebook &
$ jupyter-notebook &

然后您将在浏览器中打开两个单独的jupyter客户端,通常分别是http://localhost:8888/http://localhost:8889/,没有和带有GPU支持,您可以在其中运行相同的.ipynb笔记本并测量性能差异。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接