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


当前回答

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

import torch
torch.cuda.is_available()

参考:PyTorch | Get Started

其他回答

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

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

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

由于这里没有提出,我添加了一个使用torch.device的方法,因为这非常方便,在正确的设备上初始化张量时也是如此。

# setting device on GPU if available, else CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()

#Additional Info when using cuda
if device.type == 'cuda':
    print(torch.cuda.get_device_name(0))
    print('Memory Usage:')
    print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB')
    print('Cached:   ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB')

编辑:torch.cuda。Memory_cached已重命名为torch.cuda.memory_reserved。因此,对于旧版本使用memory_cached。

输出:

Using device: cuda

Tesla K80
Memory Usage:
Allocated: 0.3 GB
Cached:    0.6 GB

如上所述,使用设备可以:

将张量移动到相应的设备: torch.rand(10),(设备) 直接在设备上创建一个张量: 火炬。兰特(10,设备=设备)

这使得CPU和GPU之间的切换舒适,而不改变实际的代码。


编辑:

由于有一些问题和困惑的缓存和分配内存,我添加了一些关于它的额外信息:

max_memory_cached(device=None)返回缓存分配器管理的最大GPU内存,单位为字节 鉴于设备。 memory_allocated(device=None)返回给定设备的当前GPU内存使用情况(以字节为单位)。

你可以直接移交一个设备,就像上面提到的那样,或者你可以让它为None,它将使用current_device()。


附加注意:旧的图形卡与Cuda计算能力3.0或更低可能是可见的,但不能被Pytorch使用!感谢hekimgil指出这一点!“发现了GPU0 GeForce GT 750M, cuda能力3.0。PyTorch不再支持这个GPU,因为它太老了。我们支持的cuda最低能力是3.5。”

查询是否有可用的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

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

你会得到这样的结果:

使用下面的代码

import torch
torch.cuda.is_available()

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

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

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

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

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

这应该有用!