如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。
当前回答
这是可能的
torch.cuda.is_available()
返回True,但在运行时得到以下错误
>>> torch.rand(10).to(device)
MBT建议:
RuntimeError: CUDA error: no kernel image is available for execution on the device
这个链接解释了
... torch.cuda。Is_available只检查你的驱动程序是否与我们在二进制文件中使用的cuda版本兼容。这意味着CUDA 10.1与您的驱动程序是兼容的。但是当你用CUDA计算时,它找不到你的拱门的代码。
其他回答
在GPU上创建一个张量,如下所示:
$ python
>>> import torch
>>> print(torch.rand(3,3).cuda())
不要退出,打开另一个终端,检查python进程是否使用该GPU:
$ nvidia-smi
在你开始运行训练循环后,如果你想在终端上手动观察你的程序是否在利用GPU资源,以及利用到什么程度,那么你可以简单地使用watch,如下所示:
$ watch -n 2 nvidia-smi
这将持续更新使用统计每2秒,直到你按ctrl+c
如果你需要更多的GPU统计数据的控制,你可以使用更复杂的nvidia-smi版本——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=....中,以逗号分隔的查询名之间不能有空格否则,这些值将被忽略,不返回统计信息。
此外,你可以通过以下方法检查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/
使用下面的代码
import torch
torch.cuda.is_available()
将只显示GPU是否存在并被pytorch检测到。
但是在“任务管理器->性能”中,GPU利用率会非常低。
这意味着你实际上是在使用CPU运行。
解决上述问题的检查和修改:
打开硬件加速GPU设置,重新启动。 在通知区打开NVIDIA控制面板—> Desktop—>显示GPU [注意:如果您新安装了windows,那么您还必须在NVIDIA控制面板中同意这些条款和条件]
这应该有用!
在官方网站的入门页面,你可以像这样检查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
这一切都很棘手,一旦理解它,就可以帮助您快速处理较少的调试。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录