如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。
当前回答
如果你在这里是因为你的pytorch总是给torch.cuda.is_available() False,那可能是因为你安装的pytorch版本没有GPU支持。(例如:你在笔记本电脑上编码,然后在服务器上测试)。
解决方案是在pytorch下载页面中使用正确的命令卸载并重新安装pytorch。也参考这个pytorch问题。
其他回答
如果你使用的是Linux,我建议安装nvtop https://github.com/Syllo/nvtop
你会得到这样的结果:
从实际的角度来看,有一个小题外话:
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
这一切都很棘手,一旦理解它,就可以帮助您快速处理较少的调试。
在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()
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指GPU GeForce GTX 950M,目前被PyTorch选中。
推荐文章
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 在内存的哪里我的变量存储在C?
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- Visual Studio Code:如何调试Python脚本的参数