如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。


当前回答

从实际的角度来看,有一个小题外话:

import torch
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

这个开发人员现在知道是cuda还是cpu。

在使用cuda时,处理模型和张量的方式是不同的。一开始有点奇怪。

import torch
import torch.nn as nn
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
t1 = torch.randn(1,2)
t2 = torch.randn(1,2).to(dev)
print(t1)  # tensor([[-0.2678,  1.9252]])
print(t2)  # tensor([[ 0.5117, -3.6247]], device='cuda:0')
t1.to(dev)
print(t1)  # tensor([[-0.2678,  1.9252]])
print(t1.is_cuda) # False
t1 = t1.to(dev)
print(t1)  # tensor([[-0.2678,  1.9252]], device='cuda:0')
print(t1.is_cuda) # True

class M(nn.Module):
    def __init__(self):        
        super().__init__()        
        self.l1 = nn.Linear(1,2)

    def forward(self, x):                      
        x = self.l1(x)
        return x
model = M()   # not on cuda
model.to(dev) # is on cuda (all parameters)
print(next(model.parameters()).is_cuda) # True

这一切都很棘手,一旦理解它,就可以帮助您快速处理较少的调试。

其他回答

这些函数应该有助于:

>>> import torch

>>> torch.cuda.is_available()
True

>>> torch.cuda.device_count()
1

>>> torch.cuda.current_device()
0

>>> torch.cuda.device(0)
<torch.cuda.device at 0x7efce0b03be0>

>>> torch.cuda.get_device_name(0)
'GeForce GTX 950M'

这告诉我们:

CUDA是可用的,可以在一台设备上使用。 Device 0指GPU GeForce GTX 950M,目前被PyTorch选中。

Query Command
Does PyTorch see any GPUs? torch.cuda.is_available()
Are tensors stored on GPU by default? torch.rand(10).device
Set default tensor type to CUDA: torch.set_default_tensor_type(torch.cuda.FloatTensor)
Is this tensor a GPU tensor? my_tensor.is_cuda
Is this model stored on the GPU? all(p.is_cuda for p in my_model.parameters())

步骤1:导入火炬库

import torch

#步骤2:创建张量

tensor = torch.tensor([5, 6])

#步骤3:查找设备类型

#输出1:在下面的输出中,我们可以得到size(tensor.shape), dimension(tensor.ndim), #和处理张量的设备

tensor, tensor.device, tensor.ndim, tensor.shape

(tensor([5, 6]), device(type='cpu'), 1, torch.Size([2]))

#or

#输出2:在下面,输出我们可以得到的唯一设备类型

tensor.device

device(type='cpu')

#由于我的系统使用cpu处理器“第11代英特尔(R)酷睿(TM) i5-1135G7 @ 2.40GHz 2.42 GHz”

#find,如果张量处理GPU?

print(tensor, torch.cuda.is_available()

# the output will be

tensor([5, 6]) False 

#上面的输出是假的,因此它不在gpu上

#快乐编码:)

如果你在这里是因为你的pytorch总是给torch.cuda.is_available() False,那可能是因为你安装的pytorch版本没有GPU支持。(例如:你在笔记本电脑上编码,然后在服务器上测试)。

解决方案是在pytorch下载页面中使用正确的命令卸载并重新安装pytorch。也参考这个pytorch问题。

查询是否有可用的GPU。

torch.cuda.is_available()

如果上面的函数返回False,

你要么没有GPU, 或者没有安装Nvidia驱动程序,所以OS看不到GPU, 或者GPU被环境变量CUDA_VISIBLE_DEVICES隐藏。当CUDA_VISIBLE_DEVICES的值为-1时,将隐藏所有设备。你可以用下面这行代码检查这个值:os.environ['CUDA_VISIBLE_DEVICES']

如果上面的函数返回True,这并不一定意味着你正在使用GPU。在Pytorch中,您可以在创建设备时将张量分配给它们。默认情况下,张量被分配给cpu。要检查张量的分配位置,请执行以下操作:

# assuming that 'a' is a tensor created somewhere else
a.device  # returns the device where the tensor is allocated

注意,您不能操作在不同设备中分配的张量。要了解如何将张量分配给GPU,请参见这里:https://pytorch.org/docs/stable/notes/cuda.html