¿Cómo puedo obtener el uso de GPU con el código?
Ejecute el comando shell o python para obtener el uso de la GPU.
Uso del comando shell
- Ejecute el comando nvidia-smi.
Esta operación se basa en CUDA NVCC.
watch -n 1 nvidia-smi
- Ejecute el comando gpustat.
pip install gpustat
gpustat -cp -i
Para detener la ejecución del comando, presione Ctrl+C.
Uso del comando python
- Ejecute el comando nvidia-ml-py3 (comúnmente usado).
!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%} |")
- Ejecute los comandos nvidia_smi, wapper y prettytable.
Utilice el decorador para obtener el uso de la GPU en tiempo real durante el entrenamiento de modelos.
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
- Ejecute el comando pynvml.
Ejecute nvidia-ml-py3 para obtener directamente la biblioteca de c-lib de nvml, sin usar nvidia-smi. Por lo tanto, se recomienda este comando.
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)
- Ejecute el comando 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))
Al usar un framework de aprendizaje profundo como PyTorch o TensorFlow también puede usar las API proporcionadas por el framework para consultas.