1.指定GPU运算session
若是安装的是GPU版本,在运行的过程当中TensorFlow可以自动检测。若是检测到GPU,TensorFlow会尽量的利用找到的第一个GPU来执行操做。函数
若是机器上有超过一个可用的GPU,除了第一个以外的其余的GPU默认是不参与计算的。为了让TensorFlow使用这些GPU,必须将OP明确指派给他们执行。with......device语句可以用来指派特定的CPU或者GPU执行操做:spa
import tensorflow as tf import numpy as np with tf.Session() as sess: with tf.device('/cpu:0'): a = tf.placeholder(tf.int32) b = tf.placeholder(tf.int32) add = tf.add(a, b) sum = sess.run(add, feed_dict={a: 3, b: 4}) print(sum)
设备的字符串标识,当前支持的设备包括如下的几种:日志
cpu:0 机器的第一个cpu。code
gpu:0 机器的第一个gpu,若是有的话blog
gpu:1 机器的第二个gpu,依次类推内存
相似的还有tf.ConfigProto来构建一个config,在config中指定相关的GPU,而且在session中传入参数config=“本身建立的config”来指定gpu操做资源
其中,tf.ConfigProto函数的参数以下:字符串
log_device_placement=True: 是否打印设备分配日志it
allow_soft_placement=True: 若是指定的设备不存在,容许TF自动分配设备
import tensorflow as tf import numpy as np config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True) with tf.Session(config=config) as sess: a = tf.placeholder(tf.int32) b = tf.placeholder(tf.int32) add = tf.add(a, b) sum = sess.run(add, feed_dict={a: 3, b: 4}) print(sum)
2.设置GPU使用资源
上文的tf.ConfigProto函数生成的config以后,还能够设置其属性来分配GPU的运算资源,以下代码就是按需分配
import tensorflow as tf import numpy as np config = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True) config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: a = tf.placeholder(tf.int32) b = tf.placeholder(tf.int32) add = tf.add(a, b) sum = sess.run(add, feed_dict={a: 3, b: 4}) print(sum)
使用 allow_growth option,刚开始会分配少许的GPU容量,而后按须要慢慢的增长,有与不会释放内存,随意会致使内存碎片。
一样,上述的代码也能够在config建立时指定,
import tensorflow as tf import numpy as np gpu_options = tf.GPUOptions(allow_growth=True) config = tf.ConfigProto(gpu_options=gpu_options) with tf.Session(config=config) as sess: a = tf.placeholder(tf.int32) b = tf.placeholder(tf.int32) add = tf.add(a, b) sum = sess.run(add, feed_dict={a: 3, b: 4}) print(sum)
咱们还能够给gpu分配固定大小的计算资源。
gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.5)
上述代码的含义是分配给tensorflow的GPU显存大小为:GPU的实际显存*0.5