更新时间:2024-01-17 GMT+08:00
如何在代码中打印GPU使用信息
用户可通过shell命令或python命令查询GPU使用信息。
使用shell命令
使用python命令
- 执行nvidia-ml-py3命令(常用)。
!pip install nvidia-ml-py3
import nvidia_smi nvidia_smi.nvmlInit() deviceCount = nvidia_smi.nvmlDeviceGetCount() for i in range(deviceCount): handle = nvidia_smi.nvmlDeviceGetHandleByIndex(i) util = nvidia_smi.nvmlDeviceGetUtilizationRates(handle) mem = nvidia_smi.nvmlDeviceGetMemoryInfo(handle) print(f"|Device {i}| Mem Free: {mem.free/1024**2:5.2f}MB / {mem.total/1024**2:5.2f}MB | gpu-util: {util.gpu:3.1%} | gpu-mem: {util.memory:3.1%} |")
- 执行nvidia_smi + wapper + prettytable命令。
用户可以将GPU信息显示操作看作一个装饰器,在模型训练过程中就可以实时的显示GPU状态信息。
def gputil_decorator(func): def wrapper(*args, **kwargs): import nvidia_smi import prettytable as pt try: table = pt.PrettyTable(['Devices','Mem Free','GPU-util','GPU-mem']) nvidia_smi.nvmlInit() deviceCount = nvidia_smi.nvmlDeviceGetCount() for i in range(deviceCount): handle = nvidia_smi.nvmlDeviceGetHandleByIndex(i) res = nvidia_smi.nvmlDeviceGetUtilizationRates(handle) mem = nvidia_smi.nvmlDeviceGetMemoryInfo(handle) table.add_row([i, f"{mem.free/1024**2:5.2f}MB/{mem.total/1024**2:5.2f}MB", f"{res.gpu:3.1%}", f"{res.memory:3.1%}"]) except nvidia_smi.NVMLError as error: print(error) print(table) return func(*args, **kwargs) return wrapper
- 执行pynvml命令。
nvidia-ml-py3可以直接查询nvml c-lib库,而无需通过nvidia-smi。因此,这个模块比nvidia-smi周围的包装器快得多。
from pynvml import * nvmlInit() handle = nvmlDeviceGetHandleByIndex(0) info = nvmlDeviceGetMemoryInfo(handle) print("Total memory:", info.total) print("Free memory:", info.free) print("Used memory:", info.used)
- 执行gputil命令。
!pip install gputil
import GPUtil as GPU GPU.showUtilization()
import GPUtil as GPU GPUs = GPU.getGPUs() for gpu in GPUs: print("GPU RAM Free: {0:.0f}MB | Used: {1:.0f}MB | Util {2:3.0f}% | Total {3:.0f}MB".format(gpu.memoryFree, gpu.memoryUsed, gpu.memoryUtil*100, gpu.memoryTotal))
注:用户在使用pytorch/tensorflow等深度学习框架时也可以使用框架自带的api进行查询。
父主题: 更多功能咨询
更多功能咨询 所有常见问题
- 在Notebook中,如何使用昇腾多卡进行调试?
- 使用Notebook不同的资源规格,为什么训练速度差不多?
- 使用MoXing时,如何进行增量训练?
- 在Notebook中如何查看GPU使用情况
- 如何在代码中打印GPU使用信息
- Ascend上如何查看实时性能指标?
- 不启用自动停止,系统会自动停掉Notebook实例吗?会删除Notebook实例吗?
- JupyterLab目录的文件、Terminal的文件和OBS的文件之间的关系
- 如何迁移旧版Notebook数据到新版Notebook
- ModelArts中创建的数据集,如何在Notebook中使用
- pip介绍及常用命令
- 开发环境中不同Notebook规格资源“/cache”目录的大小
- 开发环境如何实现IAM用户隔离?
- 资源超分对Notebook实例有什么影响?
more