TensorFlow默認會占用設備上所有的GPU以及每個GPU的所有顯存;如果指定了某塊GPU,也會默認一次性占用該GPU的所有顯存。可以通過以下方式解決:
1 Python代碼中設置環境變量,指定GPU
本文所有代碼在tensorflow 1.12.0中測試通過。
import os os.environ["CUDA_VISIBLE_DEVICES"] = "2" # 指定只是用第三塊GPU
2 系統環境變量中指定GPU
# 只使用第2塊GPU,在demo_code.py,機器上的第二塊GPU變成”/gpu:0“,不過在運行時所有的/gpu:0的運算將被放到第二塊GPU上 CUDA_VISIBLE_DEVICES=1 python demo_code.py #只使用第一塊GPU和第二塊GPU CUDA_VISIBLE_DEVICES=0,1 python demo_code.py
3 動態分配GPU顯存
# allow_soft_placement=True 沒有GPU的話在CPU上運行 config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True) config.gpu_options.allow_growth = True # 按需分配顯存 with tf.Session(config=config) as sess: sess.run(...)
4 按固定比例分配顯存
# 按照固定的比例分配。 config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True) # 以下代碼會占用所有可使用的GPU的40%顯存 config.gpu_options.per_process_gpu_memory_fraction = 0.4 with tf.Session(config=config) as sess: sess.run(...)
在我的設備中設置后GPU占用情況如下:
gz_6237_gpu Sat Feb 15 23:01:56 2020 418.87.00 [0] GeForce RTX 2080 Ti | 43'C, 0 % | 4691 / 10989 MB | dc:python/1641(4681M)
5 通過tf.device將運算指定到特定設備上
with tf.device("/gpu:0"): b = tf.Variable(tf.zeros([1])) W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0)) y = tf.matmul(W, x_data) + b
這種方式不推薦。TF的kernel中國定義了哪些操作可以跑在GPU上,哪些不可以,因此強制指定GPU會降低程序的可移植性。
推薦的做法是:在創建會話時,指定參數allow_soft_placement=True;這樣如果運算無法在GPU上執行,TF會自動將它放在CPU上執行。
config = tf.ConfigProto(allow_soft_placement=True) with tf.Session(config=config) as sess: sess.run(...)