python - 使用 pytorch 获取可用 GPU 内存总量

标签 python pytorch gpu google-colaboratory

我正在使用 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/

相关文章:

Python:替换未知数量的字符串变量

python - 通过移动 n 个数据点找到最小值

检测 NaN 的 Pytorch 操作

arrays - arrayfun 具有具有不同维度输入的函数

GPU L1 缓存一致性

python - 如何将多个 Pandas DataFrame 存储在一起

c++ - 在 Cython 中做列表/字典的惯用方式?

python - PyTorch 中多输出回归问题的 RMSE 损失

python - 如何优化推理脚本以获得更快的分类器预测?

c - 如何确定缓冲区是在 GPU 还是 CPU 上?