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


当前回答

简单地从命令提示符或Linux环境中运行以下命令。

python -c 'import torch; print(torch.cuda.is_available())'

上面应该打印为True

python -c 'import torch; print(torch.rand(2,3).cuda())'

它应该打印以下内容:

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

其他回答

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())

使用下面的代码

import torch
torch.cuda.is_available()

将只显示GPU是否存在并被pytorch检测到。

但是在“任务管理器->性能”中,GPU利用率会非常低。

这意味着你实际上是在使用CPU运行。

解决上述问题的检查和修改:

打开硬件加速GPU设置,重新启动。 在通知区打开NVIDIA控制面板—> Desktop—>显示GPU [注意:如果您新安装了windows,那么您还必须在NVIDIA控制面板中同意这些条款和条件]

这应该有用!

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

import torch
torch.cuda.is_available()

参考:PyTorch | Get Started

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

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

这是可能的

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计算时,它找不到你的拱门的代码。