如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。
当前回答
步骤1:导入火炬库
import torch
#步骤2:创建张量
tensor = torch.tensor([5, 6])
#步骤3:查找设备类型
#输出1:在下面的输出中,我们可以得到size(tensor.shape), dimension(tensor.ndim), #和处理张量的设备
tensor, tensor.device, tensor.ndim, tensor.shape
(tensor([5, 6]), device(type='cpu'), 1, torch.Size([2]))
#or
#输出2:在下面,输出我们可以得到的唯一设备类型
tensor.device
device(type='cpu')
#由于我的系统使用cpu处理器“第11代英特尔(R)酷睿(TM) i5-1135G7 @ 2.40GHz 2.42 GHz”
#find,如果张量处理GPU?
print(tensor, torch.cuda.is_available()
# the output will be
tensor([5, 6]) False
#上面的输出是假的,因此它不在gpu上
#快乐编码:)
其他回答
如果你在这里是因为你的pytorch总是给torch.cuda.is_available() False,那可能是因为你安装的pytorch版本没有GPU支持。(例如:你在笔记本电脑上编码,然后在服务器上测试)。
解决方案是在pytorch下载页面中使用正确的命令卸载并重新安装pytorch。也参考这个pytorch问题。
在GPU上创建一个张量,如下所示:
$ python
>>> import torch
>>> print(torch.rand(3,3).cuda())
不要退出,打开另一个终端,检查python进程是否使用该GPU:
$ nvidia-smi
使用下面的代码
import torch
torch.cuda.is_available()
将只显示GPU是否存在并被pytorch检测到。
但是在“任务管理器->性能”中,GPU利用率会非常低。
这意味着你实际上是在使用CPU运行。
解决上述问题的检查和修改:
打开硬件加速GPU设置,重新启动。 在通知区打开NVIDIA控制面板—> Desktop—>显示GPU [注意:如果您新安装了windows,那么您还必须在NVIDIA控制面板中同意这些条款和条件]
这应该有用!
如果你使用的是Linux,我建议安装nvtop https://github.com/Syllo/nvtop
你会得到这样的结果:
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()) |