TensorFlow笔记4:显卡使用

tensorflow

tensorflow可以指定训练使用的显卡。如果一台电脑具有多个NVIDIA的GPUs,用户想要指定需要使用的GPU,那么在python中可以写如下语句。这个语句设置了当前程序可见的显卡。

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

然后使用tf.device来指定训练的gpu ID。但是如果只指定ID,而没有屏蔽掉其他的显卡的话,TF依然会占用所有的显卡资源,但是只在当前显卡下运行。

tf.device('/gpu:0')

比如

import tensorflow as tf  
with tf.device('/gpu:1'):  
    v1 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v1')  
    v2 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v2')  
    sumV12 = v1 + v2  

    with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:  
        print sess.run(sumV12) 

此外,还可以指定多显卡同时工作
参考:https://blog.csdn.net/u011961856/article/details/78011270

for gpu_ind in range(0, num_gpus):
    with tf.device("/gpu:{}".format(gpu_ind)):

或者

 for i in xrange(FLAGS.num_gpus):
     with tf.device('/gpu:%d' % i):

为了避免占用所有的显存,可以设置显存自适应,按比例的自适应方法如下:

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

或者使用按照需求的自适应

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章