对于刚刚迈入深度学习的小白,简单介绍分配GPU或者CPU的方法
1.只使用CPU
代码如下
1.1使用os模块在程序开头指定可见的设备——针对tensorflow和pytorch
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
代码含义解释:
os.environ[“CUDA_DEVICE_ORDER”] = "PCI_BUS_ID"是指:
按照PCI_BUS_ID顺序从0开始排列GPU设备
os.environ[“CUDA_VISIBLE_DEVICES”] = “-1”
这句是设置当前使用的GPU设备是CPU
1.2 在运行脚本程序的时候在终端指定——针对tensorflow和pytorch
CUDA_VISIBLE_DEVICES = 1
CUDA_VISIBLE_DEVICES = 0,1
CUDA_VISIBLE_DEVICES = 0,2,3
CUDA_VISIBLE_DEVICES = "1,2"
CUDA_VISIBLE_DEVICES = "1,2,3"
2、按照一定百分比,占用GPU进行使用
仅tensorflow的使用方式
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5 # 占用GPU50%的显存
3、指定多GPU的一个或者几个GPU
使用如下代码:
import os
os.environ['CUDA_VISIBLE_DEVICES']='3'
上面是选择某一个GPU,如果使用多个GPU,仅需换成如下形式
import os
os.environ['CUDA_VISIBLE_DEVICES']='3,4,5'
注意:这样的设定,在后面的程序中, 使用GPU3,其device的代号是0
4、pytorch中GPU常见的一些使用策略
torch.cuda.current_device() # 返回当前所选择的device的索引
torch.cuda.device_count() # 返回可使用的GPU的数量
torch.cuda.get_device_capability(device=None) # 查看某一个设备device的计算能力
torch.cuda.get_device_name(device=None) # 获取设备的名称
torch.cuda.is_available() # 查看GPU是否可用
torch.cuda.is_initialized() # 查看pytorch的 CUDA 状态是否初始化
torch.cuda.set_device(device) # 不推荐使用,可以使用前面的os的方法
为了更好的说明上面的结果,下面是我运行调试的具体结果:
>>> torch.cuda.current_device()
0
>>> torch.cuda.device_count()
8
>>> torch.cuda.get_device_capability(device=None)
(5, 2)
>>> torch.cuda.get_device_name()
'Tesla M40 24GB'
>>> torch.cuda.is_available()
True
>>> torch.cuda.is_initialized()
True
>>> import os
>>> os.environ['CUDA_VISIBLE_DEVICES']='3'
>>> torch.cuda.current_device()
0
5、pytorch的简单测试代码
torch.__version__
torch.version.cuda
torch.cuda.is_available()
torch.cuda.get_device_name(0)
torch.cuda.device_count()
torch.cuda.current_device()
torch.backends.cudnn.version()
>>> torch.__version__
'1.6.0+cu101'
>>> torch.version.cuda
'10.1'
>>> torch.cuda.is_available()
True
>>> torch.cuda.get_device_name(0)
'Tesla M40 24GB'
>>> torch.cuda.device_count()
8
>>> torch.cuda.current_device()
0
>>> torch.backends.cudnn.version()
7603