檢測pytorch是否使用GPU的方法小結(jié)
利用gpustat或nvidia-smi實時監(jiān)控GPU使用率
安裝gpustat
apt install gpustat
啟動gpustat
watch -n1 --color gpustat --color
每秒輸出實時監(jiān)測結(jié)果,如下圖:

也可利用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的方法小結(jié)的詳細內(nèi)容,更多關于檢測pytorch GPU方法的資料請關注腳本之家其它相關文章!
相關文章
分享一下Python數(shù)據(jù)分析常用的8款工具
Python是數(shù)據(jù)處理常用工具,可以處理數(shù)量級從幾K至幾T不等的數(shù)據(jù),具有較高的開發(fā)效率和可維護性,還具有較強的通用性和跨平臺性,這里就為大家分享幾個不錯的數(shù)據(jù)分析工具,需要的朋友可以參考下2018-04-04
Python3調(diào)用微信企業(yè)號API發(fā)送文本消息代碼示例
這篇文章主要介紹了Python3調(diào)用微信企業(yè)號API發(fā)送文本消息代碼示例,具有一定參考價值,需要的朋友可以了解下。2017-11-11

