有没有一种方式可以强制限制要分配给特定Pytorch实例的GPU内存的最大值?例如,我的GPU可能有12GB可用,但我希望将最大值分配为4GB,以供特定进程使用。
有没有一种方式可以强制限制要分配给特定Pytorch实例的GPU内存的最大值?例如,我的GPU可能有12GB可用,但我希望将最大值分配为4GB,以供特定进程使用。
master
分支中,但还没有在稳定版本中引入。
作为set_per_process_memory_fraction
引入
您可以查看测试作为使用示例。设置进程的内存分数。该分数用于限制缓存分配器在CUDA设备上分配的内存。允许的值等于总可见内存乘以该分数。如果尝试在一个进程中分配超过允许值的内存,则会在分配器中引发内存不足错误。
更新 PyTorch 到 1.8.0 版本(使用命令:pip install --upgrade torch==1.8.0)
函数:torch.cuda.set_per_process_memory_fraction(fraction, device=None)
参数:
fraction (float) – 取值范围为 0~1,表示允许使用的显存大小为总显存大小乘以 fraction。
device (torch.device 或 int, 可选) – 指定设备。如果为 None,则使用默认的 CUDA 设备。
示例:
import torch
torch.cuda.set_per_process_memory_fraction(0.5, 0)
torch.cuda.empty_cache()
total_memory = torch.cuda.get_device_properties(0).total_memory
# less than 0.5 will be ok:
tmp_tensor = torch.empty(int(total_memory * 0.499), dtype=torch.int8, device='cuda')
del tmp_tensor
torch.cuda.empty_cache()
# this allocation will raise a OOM:
torch.empty(total_memory // 2, dtype=torch.int8, device='cuda')
"""
It raises an error as follows:
RuntimeError: CUDA out of memory. Tried to allocate 5.59 GiB (GPU 0; 11.17 GiB total capacity; 0 bytes already allocated; 10.91 GiB free; 5.59 GiB allowed; 0 bytes reserved in total by PyTorch)
"""
为了使其在程序中运行,请尝试:
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"