如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。
当前回答
从实际的角度来看,有一个小题外话:
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
这一切都很棘手,一旦理解它,就可以帮助您快速处理较少的调试。
其他回答
如果你使用的是Linux,我建议安装nvtop https://github.com/Syllo/nvtop
你会得到这样的结果:
在官方网站的入门页面,你可以像这样检查PyTorch的GPU是否可用:
import torch
torch.cuda.is_available()
参考:PyTorch | Get Started
使用下面的代码
import torch
torch.cuda.is_available()
将只显示GPU是否存在并被pytorch检测到。
但是在“任务管理器->性能”中,GPU利用率会非常低。
这意味着你实际上是在使用CPU运行。
解决上述问题的检查和修改:
打开硬件加速GPU设置,重新启动。 在通知区打开NVIDIA控制面板—> Desktop—>显示GPU [注意:如果您新安装了windows,那么您还必须在NVIDIA控制面板中同意这些条款和条件]
这应该有用!
在GPU上创建一个张量,如下所示:
$ python
>>> import torch
>>> print(torch.rand(3,3).cuda())
不要退出,打开另一个终端,检查python进程是否使用该GPU:
$ nvidia-smi
这里几乎所有的答案都引用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
推荐文章
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?