tensorflow使用指定gpu的方法


Posted in Python onFebruary 04, 2020

TensorFlow是一个基于数据流编程(dataflow programming)的符号数学系统,被广泛应用于各类机器学习(machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief [1]  。
Tensorflow拥有多层级结构,可部署于各类服务器、PC终端和网页并支持GPU和TPU高性能数值计算,被广泛应用于谷歌内部的产品开发和各领域的科学研究 。

TensorFlow由谷歌人工智能团队谷歌大脑(Google Brain)开发和维护,拥有包括TensorFlow Hub、TensorFlow Lite、TensorFlow Research Cloud在内的多个项目以及各类应用程序接口(Application Programming Interface, API) 。自2015年11月9日起,TensorFlow依据阿帕奇授权协议(Apache 2.0 open source license)开放源代码 。

持续监控GPU使用情况命令:

$ watch -n 10 nvidia-smi

一、指定使用某个显卡

如果机器中有多块GPU,tensorflow会默认吃掉所有能用的显存, 如果实验室多人公用一台服务器,希望指定使用特定某块GPU。
可以在文件开头加入如下代码:

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1"  # 使用第二块GPU(从0开始)

也可以制定使用某几块GPU

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0, 2" # 使用第一, 三块GPU

禁用GPU

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

支持的设备

在一套标准系统中通常有多台计算设备。TensorFlow 支持 CPU 和 GPU 这两种设备。它们均用 strings 表示。例如:

"/cpu:0":机器的 CPU。
"/device:GPU:0":机器的 GPU(如果有一个)。
"/device:GPU:1":机器的第二个 GPU(以此类推)。

如果 TensorFlow 指令中兼有 CPU 和 GPU 实现,当该指令分配到设备时,GPU 设备有优先权。例如,如果 matmul 同时存在 CPU 和 GPU 核函数,在同时有 cpu:0 和 gpu:0 设备的系统中,gpu:0 会被选来运行 matmul。

记录设备分配方式

要找出您的指令和张量被分配到哪个设备,请创建会话并将 log_device_placement 配置选项设为 True。

#Creates a graph.
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)
#Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
#Runs the op.
print(sess.run(c))

应该会看到以下输出内容:

Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K40c, pci bus
id: 0000:05:00.0
b: /job:localhost/replica:0/task:0/device:GPU:0
a: /job:localhost/replica:0/task:0/device:GPU:0
MatMul: /job:localhost/replica:0/task:0/device:GPU:0
[[ 22. 28.]
 [ 49. 64.]]

手动分配设备

如果您希望特定指令在您选择的设备(而非系统自动为您选择的设备)上运行,您可以使用 with tf.device 创建设备上下文,这个上下文中的所有指令都将被分配在同一个设备上运行。

# Creates a graph.
with tf.device('/cpu: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)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))

您会看到现在 a 和 b 被分配到 cpu:0。由于未明确指定运行 MatMul 指令的设备,因此 TensorFlow 运行时将根据指令和可用设备(此示例中的 gpu:0)选择一个设备,并会根据要求自动复制设备间的张量。

Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K40c, pci bus
id: 0000:05:00.0
b: /job:localhost/replica:0/task:0/cpu:0
a: /job:localhost/replica:0/task:0/cpu:0
MatMul: /job:localhost/replica:0/task:0/device:GPU:0
[[ 22. 28.]
 [ 49. 64.]]

允许增加 GPU 内存

默认情况下,TensorFlow 会映射进程可见的所有 GPU 的几乎所有 GPU 内存(取决于 CUDA_VISIBLE_DEVICES)。通过减少内存碎片,可以更有效地使用设备上相对宝贵的 GPU 内存资源。

在某些情况下,最理想的是进程只分配可用内存的一个子集,或者仅根据进程需要增加内存使用量。 TensorFlow 在 Session 上提供两个 Config 选项来进行控制。

第一个是 allow_growth 选项,它试图根据运行时的需要来分配 GPU 内存:它刚开始分配很少的内存,随着 Session 开始运行并需要更多 GPU 内存,我们会扩展 TensorFlow 进程所需的 GPU 内存区域。请注意,我们不会释放内存,因为这可能导致出现更严重的内存碎片情况。要开启此选项,请通过以下方式在 ConfigProto 中设置选项:

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config, ...)

第二个是 per_process_gpu_memory_fraction 选项,它可以决定每个可见 GPU 应分配到的内存占总内存量的比例。例如,您可以通过以下方式指定 TensorFlow 仅分配每个 GPU 总内存的 40%:

config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4
session = tf.Session(config=config, ...)

如要真正限制 TensorFlow 进程可使用的 GPU 内存量,这非常实用。

在多 GPU 系统中使用单一 GPU
如果您的系统中有多个 GPU,则默认情况下将选择 ID 最小的 GPU。如果您希望在其他 GPU 上运行,则需要显式指定偏好设置:

# Creates a graph.
with tf.device('/device:GPU:2'):
 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)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))

如果您指定的设备不存在,您会看到 InvalidArgumentError:

InvalidArgumentError: Invalid argument: Cannot assign a device to node 'b':
Could not satisfy explicit device specification '/device:GPU:2'
 [[Node: b = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [3,2]
 values: 1 2 3...>, _device="/device:GPU:2"]()]]

当指定设备不存在时,如果您希望 TensorFlow 自动选择现有的受支持设备来运行指令,则可以在创建会话时将配置选项中的 allow_soft_placement 设为 True。

# Creates a graph.
with tf.device('/device:GPU:2'):
 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)
# Creates a session with allow_soft_placement and log_device_placement set
# to True.
sess = tf.Session(config=tf.ConfigProto(
  allow_soft_placement=True, log_device_placement=True))
# Runs the op.
print(sess.run(c))

使用多个 GPU

如果您想要在多个 GPU 上运行 TensorFlow,则可以采用多塔式方式构建模型,其中每个塔都会分配给不同 GPU。例如:

# Creates a graph.
c = []
for d in ['/device:GPU:2', '/device:GPU:3']:
 with tf.device(d):
 a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3])
 b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2])
 c.append(tf.matmul(a, b))
with tf.device('/cpu:0'):
 sum = tf.add_n(c)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(sum))

您会看到以下输出内容:

Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K20m, pci bus
id: 0000:02:00.0
/job:localhost/replica:0/task:0/device:GPU:1 -> device: 1, name: Tesla K20m, pci bus
id: 0000:03:00.0
/job:localhost/replica:0/task:0/device:GPU:2 -> device: 2, name: Tesla K20m, pci bus
id: 0000:83:00.0
/job:localhost/replica:0/task:0/device:GPU:3 -> device: 3, name: Tesla K20m, pci bus
id: 0000:84:00.0
Const_3: /job:localhost/replica:0/task:0/device:GPU:3
Const_2: /job:localhost/replica:0/task:0/device:GPU:3
MatMul_1: /job:localhost/replica:0/task:0/device:GPU:3
Const_1: /job:localhost/replica:0/task:0/device:GPU:2
Const: /job:localhost/replica:0/task:0/device:GPU:2
MatMul: /job:localhost/replica:0/task:0/device:GPU:2
AddN: /job:localhost/replica:0/task:0/cpu:0
[[ 44. 56.]
 [ 98. 128.]]

cifar10 教程就是个很好的例子,演示了如何使用多个 GPU 进行训练。

见官方教程:https://www.tensorflow.org/programmers_guide/using_gpu?hl=zh-cn

总结

以上所述是小编给大家介绍的tensorflow使用指定gpu的方法,希望对大家有所帮助!

Python 相关文章推荐
有关wxpython pyqt内存占用问题分析
Jun 09 Python
python 字典(dict)遍历的四种方法性能测试报告
Jun 25 Python
Python自动化构建工具scons使用入门笔记
Mar 10 Python
C#返回当前系统所有可用驱动器符号的方法
Apr 18 Python
python下MySQLdb用法实例分析
Jun 08 Python
windows10系统中安装python3.x+scrapy教程
Nov 08 Python
Python利用QQ邮箱发送邮件的实现方法(分享)
Jun 09 Python
详解django中自定义标签和过滤器
Jul 03 Python
django从请求到响应的过程深入讲解
Aug 01 Python
让你的Python代码实现类型提示功能
Nov 19 Python
解决pytorch报错:AssertionError: Invalid device id的问题
Jan 10 Python
Python re.sub 反向引用的实现
Jul 07 Python
TensorFlow梯度求解tf.gradients实例
Feb 04 #Python
基于TensorFlow中自定义梯度的2种方式
Feb 04 #Python
tensorflow 查看梯度方式
Feb 04 #Python
opencv python图像梯度实例详解
Feb 04 #Python
TensorFlow设置日志级别的几种方式小结
Feb 04 #Python
Python 实现加密过的PDF文件转WORD格式
Feb 04 #Python
解决tensorflow打印tensor有省略号的问题
Feb 04 #Python
You might like
也谈 PHP 和 MYSQL
2006/10/09 PHP
PHP 编程请选择正确的文本编辑软件
2006/12/21 PHP
Linux下手动编译安装PHP扩展的例子分享
2014/07/15 PHP
PHP函数引用返回的实例详解
2016/09/11 PHP
thinkPHP框架中执行事务的方法示例
2018/05/31 PHP
图片自动更新(说明)
2006/10/02 Javascript
用js写了一个类似php的print_r输出换行功能
2013/02/18 Javascript
document.write()及其输出内容的样式、位置控制
2013/08/12 Javascript
js为空或不是对象问题的快速解决方法
2013/12/11 Javascript
分享一则JavaScript滚动条插件源码
2015/03/03 Javascript
js获取新浪天气接口的实现代码
2016/06/06 Javascript
使用AngularJS2中的指令实现按钮的切换效果
2017/03/27 Javascript
jQuery实现左右滑动的toggle方法
2018/03/03 jQuery
解决vue this.$forceUpdate() 处理页面刷新问题(v-for循环值刷新等)
2018/07/26 Javascript
从0到1搭建element后台框架优化篇(打包优化)
2019/05/12 Javascript
Vue+Element实现动态生成新表单并添加验证功能
2019/05/23 Javascript
Vue实现拖放排序功能的实例代码
2019/07/08 Javascript
websocket4.0+typescript 实现热更新的方法
2019/08/14 Javascript
在vue中利用全局路由钩子给url统一添加公共参数的例子
2019/11/01 Javascript
[00:53]TI3正赛第三天 DK怒破A队不败金身 现场国旗飘扬热血激昂
2013/08/10 DOTA
python常用web框架简单性能测试结果分享(包含django、flask、bottle、tornado)
2014/08/25 Python
pandas数据处理基础之筛选指定行或者指定列的数据
2018/05/03 Python
对Xpath 获取子标签下所有文本的方法详解
2019/01/02 Python
Python创建或生成列表的操作方法
2019/06/19 Python
Python3爬虫发送请求的知识点实例
2020/07/30 Python
查询优化的一般准则有哪些
2015/03/08 面试题
汽车销售顾问求职自荐信
2014/01/01 职场文书
项目开发计划书
2014/01/09 职场文书
物流管理毕业生自荐信范文
2014/03/15 职场文书
护士长竞聘书
2014/03/31 职场文书
廉政文化进校园广播稿
2014/10/20 职场文书
群众路线教育实践活动总结
2014/10/30 职场文书
美术教师个人总结
2015/02/06 职场文书
酒店保洁员岗位职责
2015/02/26 职场文书
2015年安全工作总结范文
2015/04/02 职场文书
MySQL sql_mode的使用详解
2021/05/08 MySQL