欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

基于tensorflow指定GPU运行及GPU资源分配的几种方式小结

时间:2021-03-18 09:47:04|栏目:Python代码|点击:

1. 在终端执行时设置使用哪些GPU(两种方式)

(1) 如下(export 语句执行一次就行了,以后再运行代码不用执行)

(2) 如下

2. 代码中指定(两种方式)

(1)

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

(2)

# Creates a graph.
with tf.device('/gpu:1'):
 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)

若想使用多个GPU,如下

c = []
for d in ['/gpu:0', '/gpu:1']:
 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)

3.GPU资源分配

(1) 设置允许GPU增长

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

(2) 设置每个GPU内存使用多少

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

上一篇:python GUI库图形界面开发之PyQt5窗口布局控件QStackedWidget详细使用方法

栏    目:Python代码

下一篇:基于python yield机制的异步操作同步化编程模型

本文标题:基于tensorflow指定GPU运行及GPU资源分配的几种方式小结

本文地址:http://www.codeinn.net/misctech/83403.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有