如何检查pytorch是否正在使用GPU?

How to check if pytorch is using the GPU?

如何检查 pytorch 是否正在使用 GPU?可以使用 nvidia-smi 检测在此过程中是否有任何来自 GPU 的 activity,但我想要用 python 脚本编写的内容。

这些函数应该有帮助:

>>> 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指的是GPUGeForce GTX 950M,目前PyTorch选择的是

启动运行训练循环后,如果您想手动从终端观察您的程序是否正在使用 GPU 资源以及使用到什么程度,那么你可以简单地使用 watch 如:

$ watch -n 2 nvidia-smi

这将每 2 秒持续更新一次使用统计信息,直到您按下 ctrl+c


如果您需要对可能需要的更多 GPU 统计数据进行更多控制,可以使用 more sophisticated version of nvidia-smi with --query-gpu=...。下面是一个简单的说明:

$ watch -n 3 nvidia-smi --query-gpu=index,gpu_name,memory.total,memory.used,memory.free,temperature.gpu,pstate,utilization.gpu,utilization.memory --format=csv

这将输出如下统计信息:

注意--query-gpu=...中逗号分隔的查询名称之间不应有任何space。否则这些值将被忽略并且不会返回任何统计信息。


此外,您可以通过执行以下操作检查 PyTorch 安装是否正确检测到 CUDA 安装:

In [13]: import  torch

In [14]: torch.cuda.is_available()
Out[14]: True

True 状态意味着 PyTorch 配置正确并且 使用 GPU,尽管您必须 move/place 在代码中包含必要语句的张量。


如果您想在 Python 代码中执行此操作,请查看此模块:

https://github.com/jonsafari/nvidia-ml-py or in pypi here: https://pypi.python.org/pypi/nvidia-ml-py/

在GPU上创建张量如下:

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

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

$ nvidia-smi

从官方网站的入门页面,您可以检查 GPU 是否可用于 PyTorch,如下所示:

import torch
torch.cuda.is_available()

参考:PyTorch | Get Started

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

# 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

如上所述,使用device 可以:

  • 移动张量到各自的device:

      torch.rand(10).to(device)
    
  • 直接在device上创建张量:

      torch.rand(10, device=device)
    

这使得在 CPUGPU 之间切换很舒服,而无需更改实际代码。


编辑:

由于对 cachedallocated 内存存在一些疑问和困惑,我添加了一些关于它的附加信息:


您可以直接交出 device,如上文所述 post,也可以留下 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()

如上函数returnsFalse,

  1. 你要么没有 GPU,
  2. 或者 Nvidia 驱动程序没有安装,所以 OS 看不到 GPU,
  3. 或者GPU被环境变量CUDA_VISIBLE_DEVICES隐藏了。当CUDA_VISIBLE_DEVICES 的值为-1 时,表示您的所有设备都被隐藏。您可以使用以下行检查代码中的值:os.environ['CUDA_VISIBLE_DEVICES']

如果是上面的函数returns 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

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

解决方案是使用 pytorch 的正确命令卸载并重新安装 pytorch downloads page. Also refer this pytorch 问题。

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

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

这个 dev 现在知道是 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.cuda.is_available()。然而,这只是硬币的一部分。它告诉您 GPU(实际上是 CUDA)是否可用,而不是它是否实际被使用。在一个典型的设置中,你会用这样的东西设置你的设备:

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

但在更大的环境(例如研究)中,为用户提供更多选项也很常见,因此他们可以根据输入禁用 CUDA、指定 CUDA ID 等。在这种情况下,是否使用 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')
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。

要解决上述问题,请检查并更改:

  1. 图形设置 --> 打开硬件加速 GPU 设置,重新启动。
  2. 打开NVIDIA控制面板-->桌面-->在通知区域显示GPU [注意:如果您是新安装的 windows 那么您还必须同意 NVIDIA 控制面板中的条款和条件]

这应该行得通!

有可能

torch.cuda.is_available()

到returnTrue但是在运行

时出现如下错误
>>> torch.rand(10).to(device)

根据 MBT 的建议:

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

This link 解释说

... torch.cuda.is_available only checks whether your driver is compatible with the version of cuda we used in the binary. So it means that CUDA 10.1 is compatible with your driver. But when you do computation with CUDA, it couldn't find the code for your arch.

如果您正在使用 Linux 我建议安装 nvtop https://github.com/Syllo/nvtop

你会得到这样的东西: