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


当前回答

在GPU上创建一个张量,如下所示:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

不要退出,打开另一个终端,检查python进程是否使用该GPU:

$ nvidia-smi

其他回答

在GPU上创建一个张量,如下所示:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

不要退出,打开另一个终端,检查python进程是否使用该GPU:

$ nvidia-smi

这是可能的

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

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

这里几乎所有的答案都引用torch.cuda.is_available()。然而,这只是硬币的一部分。它告诉你GPU(实际上是CUDA)是否可用,而不是它是否实际被使用。在一个典型的设置中,你会像这样设置你的设备:

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

但在更大的环境中(例如研究),通常也会给用户更多的选择,因此根据输入,他们可以禁用CUDA,指定CUDA id,等等。在这种情况下,是否使用GPU不仅仅取决于GPU是否可用。在设备被设置为torch设备之后,您可以获取它的type属性来验证它是否是CUDA。

if device.type == 'cuda':
    # do something

使用下面的代码

import torch
torch.cuda.is_available()

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

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

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

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

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

这应该有用!