TensorFlow GPU 的使用

1、TensorFlow 设备分配

一、设备分配规则

If a TensorFlow operation has both CPU and GPU implementations, the GPU devices will be given priority when the operation is assigned to a device.session

二、手动指定设备分配

  • 若是你不想让系统自动为 operation 分配设备, 而是本身手动指定, 能够用 with tf.device 建立一个设备环境, 这个环境下的 operation 都统一运行在指定的设备上.
  • 代码示例以下:
 1 # op 在 cpu 上运算
 2 with tf.device('/cpu:0'):
 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 6 # op 在 gpu 上运算 7 with tf.device('/device:GPU:2'): 8 a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') 9 b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') 10 11 # op 在 gpus 上运算 12 for d in ['/device:GPU:2', '/device:GPU:3']: 13  with tf.device(d): 14 a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3]) 15 b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2])

2、TensorFlow GPU 配置

一、指定能够被看见的GPU设备spa

1 import os
2 
3 # 默认状况,TF 会占用全部 GPU 的全部内存, 咱们能够指定
4 # 只有 GPU0 和 GPU1 这两块卡被看到,从而达到限制其使用全部GPU的目的
5 os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1'  
6 
7 # 打印 TF 可用的 GPU
8 print os.environ['CUDA_VISIBLE_DEVICES'] 9 >>> 0, 1

 二、限定使用显存的比例code

 1 # 在开启对话session前,先建立一个 tf.ConfigProto() 实例对象
 2 # 经过 allow_soft_placement 参数自动将没法放在 GPU 上的操做放回 CPU
 3 gpuConfig = tf.ConfigProto(allow_soft_placement=True)
 4 
 5 # 限制一个进程使用 60% 的显存
 6 gpuConfig.gpu_options.per_process_gpu_memory_fraction = 0.6
 7 
 8 # 把你的配置部署到session
 9 with tf.Session(config=gpuConfig) as sess: 10 pass 11 12 这样,若是你指定的卡的显存是8000M的话,你这个进程只能用4800M。

三、须要多少拿多少

 1 # 在开启对话session前,先建立一个 tf.ConfigProto() 实例对象
 2 # 经过 allow_soft_placement 参数自动将没法放在 GPU 上的操做放回 CPU
 3 gpuConfig = tf.ConfigProto(allow_soft_placement=True)
 4 
 5 # 运行时须要多少再给多少
 6 gpuConfig.gpu_options.allow_growth = True 7 8 # 把你的配置部署到session 9 with tf.Session(config=gpuConfig) as sess: 10 pass

  四、GPU 使用总结

1 import os
2 os.environ['CUDA_VISIBLE_DEVICES'] = '0, 1'  
3 
4 gpuConfig = tf.ConfigProto(allow_soft_placement=True) 5 gpuConfig.gpu_options.allow_growth = True 6 7 with tf.Session(config=gpuConfig) as sess: 8 pass
相关文章
相关标签/搜索