1. 在终端执行时设置使用哪些GPU(两种方式)
    (1) 如下(export 语句执行一次就行了,以后再运行代码不用执行)
    基于tensorflow指定GPU运行及GPU资源分配的几种方式小结 - 图1
    (2) 如下
    基于tensorflow指定GPU运行及GPU资源分配的几种方式小结 - 图2
    2. 代码中指定(两种方式)
    (1)

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

    (2)

    1. # Creates a graph.
    2. with tf.device('/gpu:1'):
    3. a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
    4. b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
    5. c = tf.matmul(a, b)
    6. # Creates a session with log_device_placement set to True.
    7. sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
    8. # Runs the op.
    9. print sess.run(c)

    若想使用多个GPU,如下

    1. c = []
    2. for d in ['/gpu:0', '/gpu:1']:
    3. with tf.device(d):
    4. a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3])
    5. b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2])
    6. c.append(tf.matmul(a, b))
    7. with tf.device('/cpu:0'):
    8. sum = tf.add_n(c)
    9. # Creates a session with log_device_placement set to True.
    10. sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
    11. # Runs the op.
    12. print sess.run(sum)

    3.GPU资源分配
    (1) 设置允许GPU增长

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

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

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

    以上这篇基于tensorflow指定GPU运行及GPU资源分配的几种方式小结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。