我正在使用 google colab 免费 Gpu 进行实验,并想知道有多少 GPU 内存可供使用,torch.cuda.memory_allocated() 返回当前占用的 GPU 内存,但我们如何使用 PyTorch 确定总可用内存.
最佳答案
PyTorch 可以为您提供全部、保留和分配的信息:
t = torch.cuda.get_device_properties(0).total_memory
r = torch.cuda.memory_reserved(0)
a = torch.cuda.memory_allocated(0)
f = r-a # free inside reserved
Python 与 NVIDIA 的绑定(bind)可以为您带来整个 GPU 的信息(本例中的 0 表示第一个 GPU 设备):
from pynvml import *
nvmlInit()
h = nvmlDeviceGetHandleByIndex(0)
info = nvmlDeviceGetMemoryInfo(h)
print(f'total : {info.total}')
print(f'free : {info.free}')
print(f'used : {info.used}')
pip 安装 pynvml
您可以检查nvidia-smi
以获取内存信息。
您可以使用 nvtop,但该工具需要从源代码安装(在撰写本文时)。
另一个可以检查内存的工具是 gpustat (pip3 install gpustat
)。
如果您想使用 C++ cuda:
include <iostream>
#include "cuda.h"
#include "cuda_runtime_api.h"
using namespace std;
int main( void ) {
int num_gpus;
size_t free, total;
cudaGetDeviceCount( &num_gpus );
for ( int gpu_id = 0; gpu_id < num_gpus; gpu_id++ ) {
cudaSetDevice( gpu_id );
int id;
cudaGetDevice( &id );
cudaMemGetInfo( &free, &total );
cout << "GPU " << id << " memory: free=" << free << ", total=" << total << endl;
}
return 0;
}
关于python - 使用 pytorch 获取可用 GPU 内存总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58216000/