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


当前回答

如果你使用的是Linux,我建议安装nvtop https://github.com/Syllo/nvtop

你会得到这样的结果:

其他回答

这是可能的

torch.cuda.is_available()

返回True,但在运行时得到以下错误

>>> torch.rand(10).to(device)

MBT建议:

RuntimeError: CUDA error: no kernel image is available for execution on the device

这个链接解释了

... torch.cuda。Is_available只检查你的驱动程序是否与我们在二进制文件中使用的cuda版本兼容。这意味着CUDA 10.1与您的驱动程序是兼容的。但是当你用CUDA计算时,它找不到你的拱门的代码。

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

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

在官方网站的入门页面,你可以像这样检查PyTorch的GPU是否可用:

import torch
torch.cuda.is_available()

参考:PyTorch | Get Started

步骤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上

#快乐编码:)

如果你使用的是Linux,我建议安装nvtop https://github.com/Syllo/nvtop

你会得到这样的结果: