如何检查 pytorch
是否正在使用 GPU?可以使用 nvidia-smi
检测在此过程中是否有来自 GPU 的任何活动,但我希望在 python
脚本中编写一些内容。
devices = torch.get_all_devices() # [0, 1, 2] or whatever their name is
之类的东西
[torch.cuda.device(i) for i in range(torch.cuda.device_count())]
list(range(torch.cuda.device_count()))
。不过谢谢!
import torch
):devices = [d for d in range(torch.cuda.device_count())]
如果您想要名称:device_names = [torch.cuda.get_device_name(d) for d in devices]
您可能像我一样,喜欢将这些映射为 dict 以进行跨机器管理:device_to_name = dict( device_names, devices )
这些功能应该有助于:
>>> 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 可用并且可由一台设备使用。
设备 0 指的是 GPU GeForce GTX 950M,目前由 PyTorch 选择。
由于这里没有提出,我正在添加一个使用 torch.device
的方法,因为这非常方便,在正确的 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
如上所述,使用 device
可以:
将张量移动到相应的设备:torch.rand(10).to(device)
直接在设备上创建张量:torch.rand(10, device=device)
这使得 CPU 和 GPU 之间的切换很舒服,而无需更改实际代码。
编辑:
由于对缓存和分配的内存存在一些问题和困惑,我正在添加一些关于它的附加信息:
torch.cuda.max_memory_cached(device=None) 返回给定设备的缓存分配器管理的最大 GPU 内存(以字节为单位)。
torch.cuda.memory_allocated(device=None) 返回给定设备的张量的当前 GPU 内存使用情况(以字节为单位)。
您可以直接交出上述帖子中进一步指定的 device
,也可以将其保留为 无,它将使用 current_device()
。
附加说明:具有 Cuda 计算能力 3.0 或更低版本的旧显卡可能可见,但 Pytorch 无法使用!
感谢hekimgil指出这一点! - “找到 GPU0 GeForce GT 750M,它的 cuda 能力为 3.0。PyTorch 不再支持这个 GPU,因为它太旧了。我们支持的最低 cuda 能力是 3.5。”
my_tensor_on_gpu * my_tensor_on_cpu
这样的任何操作都会失败。
Found GPU0 GeForce GT 750M which is of cuda capability 3.0. PyTorch no longer supports this GPU because it is too old. The minimum cuda capability that we support is 3.5.
torch.cuda.device_count()
其中 list(range(torch.cuda.device_count()))
应该为您提供所有设备索引的列表。
在您开始运行训练循环后,如果您想手动从终端查看您的程序是否正在使用 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
这将输出如下统计信息:
https://i.stack.imgur.com/AxUa6.png
注意:--query-gpu=...
中逗号分隔的查询名称之间不应有任何空格。否则这些值将被忽略并且不返回任何统计信息。
此外,您可以通过执行以下操作检查您的 PyTorch 安装是否正确检测到您的 CUDA 安装:
In [13]: import torch
In [14]: torch.cuda.is_available()
Out[14]: True
True
状态表示 PyTorch 配置正确并且正在使用 GPU,尽管您必须在代码中使用必要的语句移动/放置张量。
如果您想在 Python 代码中执行此操作,请查看此模块:
https://github.com/jonsafari/nvidia-ml-py 或在 pypi 中:https://pypi.python.org/pypi/nvidia-ml-py/
watch
很有用
watch
: nvidia-smi -l 2
或以毫秒为单位:nvidia-smi -lms 2000
从实际的角度来看,只有一个小题外话:
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
这一切都很棘手,理解一次,可以帮助您快速处理更少的调试。
import torch.nn as nn
从官方网站的入门页面,您可以检查 GPU 是否可用于 PyTorch,如下所示:
import torch
torch.cuda.is_available()
查询命令 PyTorch 是否看到任何 GPU? torch.cuda.is_available() 张量是否默认存储在 GPU 上? torch.rand(10).device 将默认张量类型设置为 CUDA:torch.set_default_tensor_type(torch.cuda.FloatTensor) 这个张量是 GPU 张量吗? my_tensor.is_cuda 这个模型是否存储在 GPU 上?全部(p.is_cuda for p in my_model.parameters())
检查是否有可用的 GPU:
torch.cuda.is_available()
如果上述函数返回 False
,
您要么没有 GPU,要么没有安装 Nvidia 驱动程序,因此操作系统看不到 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
这里几乎所有的答案都参考了 torch.cuda.is_available()
。然而,这只是硬币的一部分。它告诉您 GPU(实际上是 CUDA)是否可用,而不是它是否实际被使用。在典型设置中,您可以使用以下方式设置设备:
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
但在更大的环境(例如研究)中,通常也会为用户提供更多选项,因此他们可以根据输入禁用 CUDA、指定 CUDA ID 等。在这种情况下,是否使用 GPU 不仅仅取决于它是否可用。将设备设置为手电筒设备后,您可以获取其 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 总是为 torch.cuda.is_available()
提供 False
,那可能是因为您安装了没有 GPU 支持的 pytorch 版本。 (例如:您在笔记本电脑上编写代码,然后在服务器上进行测试)。
解决方案是使用 pytorch downloads 页面中的正确命令再次卸载并安装 pytorch。另请参阅 this 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
This link 解释说
... torch.cuda.is_available 仅检查您的驱动程序是否与我们在二进制文件中使用的 cuda 版本兼容。所以这意味着 CUDA 10.1 与您的驱动程序兼容。但是当您使用 CUDA 进行计算时,它找不到您的拱门的代码。
在 GPU 上创建一个张量,如下所示:
$ python
>>> import torch
>>> print(torch.rand(3,3).cuda())
不要退出,打开另一个终端并检查 python 进程是否正在使用 GPU:
$ nvidia-smi
nvidia-smi
的解决方案
nvidia-smi
。
使用下面的代码
import torch
torch.cuda.is_available()
只会显示 GPU 是否存在并被 pytorch 检测到。
但是在“任务管理器-> 性能”中,GPU 利用率将只有很少的百分比。
这意味着您实际上正在使用 CPU 运行。
要解决上述问题检查和更改:
图形设置 --> 打开硬件加速 GPU 设置,重启。打开 NVIDIA 控制面板 --> 桌面 --> 在通知区域显示 GPU [注意:如果您有新安装的 Windows,则还必须同意 NVIDIA 控制面板中的条款和条件]
这应该工作!
不定期副业成功案例分享
torch.cuda.current_device()
对我很有帮助。它表明我的 gpu 太旧了:“发现 GPU0 GeForce GTX 760 具有 cuda 能力 3.0。PyTorch 不再支持此 GPU,因为它太旧了。”torch.cuda.is_available()
$ watch -n 2 nvidia-smi
就可以了。有关详细信息,请参阅my answer below。