如何检查PyTorch是否使用GPU?nvidia-smi命令可以检测GPU活动,但我想直接从Python脚本中检查它。
当前回答
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()) |
其他回答
这些函数应该有助于:
>>> 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选中。
在官方网站的入门页面,你可以像这样检查PyTorch的GPU是否可用:
import torch
torch.cuda.is_available()
参考:PyTorch | Get Started
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()) |
查询是否有可用的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资源,以及利用到什么程度,那么你可以简单地使用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/
推荐文章
- 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脚本的参数