python&Keras实现多GPU或指定GPU的使用

1. keras新版本中加入多GPU并行使用的函数
下面程序段即可实现一个或多个GPU加速: 
注意:使用多GPU加速时,Keras版本必须是Keras2.0.9以上版本

from keras.utils.training_utils import multi_gpu_model   #导入keras多GPU函数
import VGG19     #导入已经写好的函数模型,例如VGG19

if G <= 1:
    print("[INFO] training with 1 GPU...")
    model = VGG19()

# otherwise, we are compiling using multiple GPUs
else:
    print("[INFO] training with {} GPUs...".format(G))
    # we'll store a copy of the model on *every* GPU and then combine
    # the results from the gradient updates on the CPU
    with tf.device("/cpu:0"):
        # initialize the model
        model1 = VGG19()
        # make the model parallel(if you have more than 2 GPU)
        model = multi_gpu_model(model1, gpus=G)

2.指定使用某个GPU
首先在终端查看主机中GPU编号:

watch -n -9 nvidia-smi

查询结果如下所示: 
 
显示主机中只有一块GPU,编号为0

2.1 下面方法是直接在终端运行时加入相关语句实现指定GPU的使用
export CUDA_VISIBLE_DEVICES=0 python test.py
# 表示运行test.py文件时,使用编号为0的GPU卡
export CUDA_VISIBLE_DEVICES=0,2 python test.py
# 表示运行test.py文件时,使用编号为0和2的GPU卡

2.2 下面方法是在Python程序中添加
import os
# 使用第一张与第三张GPU卡
os.environ["CUDA_VISIBLE_DEVICES"] = "0, 2"
 

猜你喜欢

转载自blog.csdn.net/qiqzhang/article/details/85455197