我正在使用Google Colab提供的免费GPU进行实验,想知道可以用多少GPU内存进行测试。通过调用torch.cuda.memory_allocated()可以返回当前已经占用的GPU内存,但是如何确定PyTorch中总共可用的内存呢?
我正在使用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可以为您提供整个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 install 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;
}
https://pytorch.org/docs/stable/generated/torch.cuda.mem_get_info.html#torch.cuda.mem_get_info
torch.cuda.mem_get_info()
total_memory
+ 保留/分配),因为它在其他进程/用户共享GPU并占用内存时提供正确的数字。 - krassowskiwith torch.cuda.device(device):
info = torch.cuda.mem_get_info()
参见:https://github.com/pytorch/pytorch/issues/76224 - אלימלך שרייבר这对我很有用!
def get_memory_free_MiB(gpu_index):
pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(int(gpu_index))
mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
return mem_info.free // 1024 ** 2
torch.cuda.memory_cached
已更名为torch.cuda.memory_reserved
。 - Kallzvximport pynvml
代替from pynvml import *
,否则可能会与其他代码发生冲突。例如,modeling_roberta.py会抛出TypeError: '_ctypes.UnionType' object is not subscriptable
。pynvml.nvmlInit()
,h = pynvml.nvmlDeviceGetHandleByIndex(0)
,info = pynvml.nvmlDeviceGetMemoryInfo(h)
。 - user2585501