模型训练,GPU的使用

Tensorflow

  • 1.在运行之前先查看GPU的使用情况:
    指令:nvidia-smi备注:查看GPU此时的使用情况
    或者
    指令:watch nvidia-smi备注:实时返回GPU使用情况
  • 2.指定GPU训练:
    方法一、在python程序中设置:
    代码:os.environ['CUDA_VISIBLE_DEVICES'] = '0' 备注:使用 GPU 0
    代码:os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' 备注:使用 GPU 0,1
    方法二、在执行python程序时候:
    指令:CUDA_VISIBLE_DEVICES=2 python yourcode.py
    指令:CUDA_VISIBLE_DEVICES=0,1 python yourcode.py
    备注:‘=’的左右不允许有空格

注:TensorFlow会默认直接占满我们模型部署的GPU的存储资源,只允许一个小内存的程序也会占用所有GPU资源。因此有的时候我们通过nvidia-smi查看GPU状态的时候,会发现有些GPU的计算利用率很低或者计算利用率为0,但是存储被占满了,而这个时候其他人也不能使用这块GPU。但是现在公司的问题是模型多,卡不够用,所有只能“文明”使用GPU,如果设置为允许动态增长的话,这样这个GPU没有被占的存储还可以被其他人使用。

  • 3.两种限定GPU占用量的方法:
    方法一、设置定量的GPU显存使用量:
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.4 # 占用GPU40%的显存
    session = tf.Session(config=config)
    方法二、设置最小的GPU显存使用量,动态申请显存:(建议)
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    session = tf.Session(config=config)

Pytorch

    1. 告诉程序哪些GPU可以使用
      import os
      os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
      os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
    1. 使用多GPU训练网络
      方法一、使用 torch.nn.DataParallel。这种方法会出负载不均衡的问题,因为当并行计算时,loss每次都在第一个GPU里相加计算,这样第一张卡会用的明显多。
import torch.nn as nn
## 判断使用cpu还是gpu
def get_device():
    if torch.cuda.is_available():
        return torch.device('cuda:0')
    else:
        return torch.device('cpu')

if torch.cuda.device_count() > 1:#判断是不是有多个GPU
    print("Let's use", torch.cuda.device_count(), "GPUs!")
    # 就这一行
    model = nn.DataParallel(model,device_ids=range(torch.cuda.device_count())) # device_ids=[0, 1, 2]

   方法二、使用distributedDataparallel
   官方链接如下:https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel 。这个函数的主要目的是为了多机多卡加速的,但是单机多卡也是没问题的。相比于之前的Dataparallel,新的函数更加优雅,速度更加快(这一点官方文档里有提到),而且不会出现负载不均衡的问题,唯一的小缺点可能就是配置稍微有点小麻烦。

Pytorch 中分布式的基本使用流程如下:

  • 1、在使用 distributed 包的任何其他函数之前,需要使用 init_process_group 初始化进程组,同时初始化 distributed 包。
  • 2、如果需要进行小组内集体通信,用 new_group 创建子分组
  • 3、创建分布式并行模型 DDP(model, device_ids=device_ids)
  • 4、为数据集创建 Sampler
  • 5、使用启动工具 torch.distributed.launch 在每个主机上执行一次脚本,开始训练
  • 6、使用 destory_process_group() 销毁进程组
    train_dataset最好不要用自己写的sampler,否则还需要再实现一遍分布式的数据划分方式
首先,我们需要对脚本进行升级,使其能够独立的在机器(节点)中运行。
我们想要完全实现分布式,并且在每个结点的每个GPU上独立运行进程,这一共需要8个进程。
接下来,初始化分布式后端,封装模型以及准备数据,这些数据用于在独立的数据子集中训练进程。更新后的代码如下:
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader

# Each process runs on 1 GPU device specified by the local_rank argument.
#设置local_rank参数,每个进程在local_rank参数指定的1个GPU设备上运行。
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", default=0, type=int,help='node rank for distributed training')
args = parser.parse_args()

# Initializes the distributed backend which will take care of sychronizing nodes/GPUs。
# 初始化负责同步节点/ gpu的分布式后端
torch.distributed.init_process_group(backend='nccl')

# Encapsulate the model on the GPU assigned to the current process
# 封装模型在指定给当前进程的GPU上
device = torch.device('cuda', arg.local_rank)
model = model.to(device)
distrib_model = torch.nn.parallel.DistributedDataParallel(model,
                                                          device_ids=[args.local_rank],
                                                          output_device=args.local_rank)

# Restricts data loading to a subset of the dataset exclusive to the current process
# 将数据加载限制为当前进程独占的数据集子集
sampler = DistributedSampler(dataset)

dataloader = DataLoader(dataset, sampler=sampler)
for inputs, labels in dataloader:
    predictions = distrib_model(inputs.to(device))         # Forward pass
    loss = loss_function(predictions, labels.to(device))   # Compute loss function
    loss.backward()                                        # Backward pass
    optimizer.step()                                       # Optimizer step

单机多GPU运行
python -m torch.distributed.launch --nproc_per_node=3 --nnodes=1 --node_rank=0 yourscript.py
多机多GPU运行
服务器1: python -m torch.distributed.launch --nproc_per_node=4 --nnodes=2 --node_rank=0 --master_addr="192.168.1.1" --master_port=1234 OUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other arguments of our training script)
服务器2: python -m torch.distributed.launch --nproc_per_node=4 --nnodes=2 --node_rank=1 --master_addr="192.168.1.1" --master_port=1234 OUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other arguments of our training script)
除了—node_rank参数之外,上述两个命令相同;--nproc_per_node表示你使用的1台服务器上的GPU数量。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。