檢測pytorch是否使用GPU的方法小結
利用gpustat或nvidia-smi實時監(jiān)控GPU使用率
安裝gpustat
apt install gpustat
啟動gpustat
watch -n1 --color gpustat --color
每秒輸出實時監(jiān)測結果,如下圖:
也可利用nvidia-smi實時監(jiān)控,會顯示更多的參數(shù)
$ watch -n 1 nvidia-smi --query-gpu=index,gpu_name,memory.total,memory.used,memory.free,temperature.gpu,pstate,utilization.gpu,utilization.memory --format=csv
輸出torch對應的設備
首先在python里檢查,也是大家用的最多的方式,檢查GPU是否可用(但實際并不一定真的在用)
torch.cuda.is_available()
更嚴謹一些,在程序運行的時候查看是否真的在使用GPU,插入代碼,在運行時輸出torch對應的設備,如果這里輸出的是CPU,肯定就沒有在GPU上運行了。
# setting device on GPU if available, else CPU device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) print() #Additional Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')
使用簡單全連接網(wǎng)絡檢測GPU情況
可以直接運行一個簡單的全連接網(wǎng)絡,查看GPU的使用情況:
import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary from torchvision import models class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) #此處的16*5*5為conv2經(jīng)過pooling之后的尺寸,即為fc1的輸入尺寸,在這里寫死了,因此后面的輸入圖片大小不能任意調(diào)整 self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] num_features = 1 for s in size: num_features *= s return num_features net = Net() print(net) params = list(net.parameters()) print (len(params)) print(params[0].size()) print(params[1].size()) print(params[2].size()) print(params[3].size()) print(params[4].size()) print(params[5].size()) print(params[6].size()) print(params[7].size()) print(params[8].size()) print(params[9].size()) input = torch.randn(1, 1, 32, 32) out = net(input) print(out) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') vgg = net.to(device) summary(vgg, (1, 32, 32))
后記
我的問題最后解決了,但是用的不是這三種方法,是因為我的服務器是阿里云服務器,安裝完驅(qū)動之后還要添加License,但是客服沒說,導致此后GPU利用率一直是0%,添加License之后就好了。。。
以上就是檢測pytorch是否使用GPU的方法小結的詳細內(nèi)容,更多關于檢測pytorch GPU方法的資料請關注腳本之家其它相關文章!
相關文章
opencv中顏色空間轉(zhuǎn)換函數(shù)cv2.cvtColor()使用
本文主要介紹了opencv中顏色空間轉(zhuǎn)換函數(shù)cv2.cvtColor()使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05python利用openpyxl拆分多個工作表的工作簿的方法
這篇文章主要介紹了python利用openpyxl拆分多個工作表的工作簿的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09python實現(xiàn)selenium網(wǎng)絡爬蟲的方法小結
這篇文章主要介紹了python實現(xiàn)selenium網(wǎng)絡爬蟲的方法小結,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03