天天看點

torch/tensorflow使用GPU訓練的方法對于keras對于TorchGPU情況檢視

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"
           

對于keras

  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)
           

對于Torch

好像目前來說隻能指定一塊或者全部使用,不能指定某幾塊

1.使用某一塊:

device = torch.device("cuda:0")
model.to(device)
#對張量:
mytensor = my_tensor.to(device)
           

2.使用全部:

model.cuda()
#對張量:
mytensor = my_tensor.cuda()
           

GPU情況檢視

在終端檢視主機中GPU編号:

watch -n -9 nvidia-smi
           

查詢結果如下所示:

torch/tensorflow使用GPU訓練的方法對于keras對于TorchGPU情況檢視

這裡隻有一個GPU,編号為0

顯示主機中隻有一塊GPU,編号為0

繼續閱讀