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


当前回答

这里几乎所有的答案都引用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

其他回答

简单地从命令提示符或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')

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

import torch
torch.cuda.is_available()

参考:PyTorch | Get Started

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

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

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

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

$ nvidia-smi

这些函数应该有助于:

>>> 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选中。