如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。
当前回答
简单地从命令提示符或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')
其他回答
步骤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上
#快乐编码:)
使用下面的代码
import torch
torch.cuda.is_available()
将只显示GPU是否存在并被pytorch检测到。
但是在“任务管理器->性能”中,GPU利用率会非常低。
这意味着你实际上是在使用CPU运行。
解决上述问题的检查和修改:
打开硬件加速GPU设置,重新启动。 在通知区打开NVIDIA控制面板—> Desktop—>显示GPU [注意:如果您新安装了windows,那么您还必须在NVIDIA控制面板中同意这些条款和条件]
这应该有用!
从实际的角度来看,有一个小题外话:
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。
torch.cuda.is_available()
如果上面的函数返回False,
你要么没有GPU, 或者没有安装Nvidia驱动程序,所以OS看不到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
在GPU上创建一个张量,如下所示:
$ python
>>> import torch
>>> print(torch.rand(3,3).cuda())
不要退出,打开另一个终端,检查python进程是否使用该GPU:
$ nvidia-smi
推荐文章
- 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脚本的参数