Tensorflow 在默認設定下,每當執行一個程式,
他會先將看的到的 GPU 的 Memory 給全部佔滿,
所以就算只有用到一點點,其他程式也沒辦法搶到 Memory 資源去執行。
為了不要浪費資源,我們在執行程式前要先限制這個程式可以吃的 memory size

方法如下:

1
2
3
4
import tensorflow as tf
# 設定程式只能使用 40 %的 memory 資源
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

or

1
2
3
4
config = tf.ConfigProto() 
# 該設置會自動使用最少的GPU memory 來運行程式
config.gpu_options.allow_growth = True
session = tf.Session(config=config)

可以使用以下指令來檢查GPU的使用率

1
$ nvidia-smi

結果如下:

image



How to select a single GPU
可以看到上面,就算限制了memory
但是他還是同時使用了兩個 GPU 去執行程式
如果我們想要只單純使用一個 GPU 去執行
在程式的”開頭”,我們必須加入設定

設定如下:
CUDA_VISIBLE_DEVICES 這個環境變數代表: 這個程式能看到的 GPU 有哪些

1
2
3
import os
# The GPU id to use, usually either "0" or "1";
os.environ["CUDA_VISIBLE_DEVICES"]="0";

而 GPU id 可以使用 $ nvidia-smi 來做查詢,或是使用下列語法來查詢 tensorflow 現在可以吃到的所有GPU狀態

1
2
3
4
5
from tensorflow.python.client import device_lib

def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']

結果如下:

image