网上做网站接活怎么样,青岛网站建设找,莆田专门做网站,武清网站建设公司目录 1、CPU与GPU2、数据迁移至GPU2.1 to函数使用方法 3、torch.cuda常用方法4、多GPU并行运算4.1 torch.nn.DataParallel4.2 torch.distributed加速并行训练 5、gpu总结 1、CPU与GPU CPU#xff08;Central Processing Unit, 中央处理器#xff09;#xff1a;主要包括控制… 目录 1、CPU与GPU2、数据迁移至GPU2.1 to函数使用方法 3、torch.cuda常用方法4、多GPU并行运算4.1 torch.nn.DataParallel4.2 torch.distributed加速并行训练 5、gpu总结 1、CPU与GPU CPUCentral Processing Unit, 中央处理器主要包括控制器和运算器 GPU(Graphics Processing Unit, 图形处理器)处理统一的无依赖的大规模数据运算 cpu的控制单元和存储单元要比GPU多比如我们加载的数据缓存一般都在cpu当中GPU的计算单元到比cpu多在算力方面要远远超过cpu 注意运算的数据必须在同一个处理器上如果一个数据在cpu一个在gpu上则两个数据无法进行相关的数学运算。 2、数据迁移至GPU
如果想要将数据进行处理器迁移所使用的工具是to函数并在中间选择想要迁移的处理器类型。 data一般有两种数据类型tensor、module。
2.1 to函数使用方法
to函数转换数据类型/设备
tensor.to(args, kwargs)module.to(args, kwargs) 区别 张量不执行inplace要构建一个新的张量模型执行inplace不需要等号赋值。 inplace操作inplace操作是指对数据进行原地修改的操作即直接在原始数据上进行更改而不是创建一个新的副本。在深度学习框架中许多函数和方法都支持inplace操作这意味着它们可以直接修改输入的张量或数组而不需要额外的内存来存储结果。 1、将tensor数据放到gpu上
import torch
import torch.nn as nn
device torch.device(cuda:0 if torch.cuda.is_available() else cpu) #调用gpu只需要一行代码
# tensor to cuda
# flag 0
flag 1
if flag:x_cpu torch.ones((3, 3))print(x_cpu:\ndevice: {} is_cuda: {} id: {}.format(x_cpu.device, x_cpu.is_cuda, id(x_cpu)))x_gpu x_cpu.to(device)print(x_gpu:\ndevice: {} is_cuda: {} id: {}.format(x_gpu.device, x_gpu.is_cuda, id(x_gpu)))打印结果 发现数据id地址发生了变化说明创建的新的变量存储数据。 2、module转移到gpu上
flag 1
if flag:net nn.Sequential(nn.Linear(3, 3))print(\nid:{} is_cuda: {}.format(id(net), next(net.parameters()).is_cuda))net.to(device)print(\nid:{} is_cuda: {}.format(id(net), next(net.parameters()).is_cuda))打印结果 id地址没有发生变化执行了inplace操作。
3、torch.cuda常用方法
torch.cuda.device_count()计算当前可见可用gpu数torch.cuda.get_device_name()获取gpu名称torch.cuda.manual_seed()为当前gpu设置随机种子torch.cuda.manual_seed_all()为所有可见可用gpu设置随机种子torch.cuda.set_device()设置主gpu为哪一个物理gpu不推荐 推荐 os.environ.setdefault(“CUDA_VISIBLE_DEVICES”, “2, 3”) 该方法要如何理解呢 需要理解两个概念物理gpu和逻辑gpu物理gpu是我们电脑真实存在的0、1、2、3等显卡,逻辑gpu是Python脚本可见的gpu。 当我们设置23时我们物理gpu连接的是我们真实电脑存在的第2号和第3号gpu。 4、多GPU并行运算
分发 → 并行运算 →结果回收 在AlexNet这篇网络中使用了多gpu训练在第三层卷积开始每个特征图的信息都是从2个gpu获取在2个gpu提取特征并进行训练最后再将信息汇总到一起
4.1 torch.nn.DataParallel
torch.nn.DataParallel(module, device_ids None, output_deviceNone, dim0)功能包装模型实现分发并行机制假设我们batch_size16如果有两块gpu在训练的时候将会将数据平均分发到每一个gpu上进行训练也就是每一块gpu训练8个数据。 主要参数
module: 需要包装分发的模型device_ids : 可分发的gpu默认分发到所有可见可用gpuoutput_device: 结果输出设备也就是主gpu上
代码实现
# -*- coding: utf-8 -*-# 导入必要的库
import os
import numpy as np
import torch
import torch.nn as nn# 手动选择gpu
# flag变量用于控制是否手动选择GPU或根据内存情况自动选择主GPU
# 如果flag为1则执行以下代码块
flag 1
if flag:# 手动选择GPU列表这里选择第一个GPUgpu_list [0]# 将GPU列表转换为逗号分隔的字符串形式并设置环境变量CUDA_VISIBLE_DEVICESgpu_list_str ,.join(map(str, gpu_list))os.environ.setdefault(CUDA_VISIBLE_DEVICES, gpu_list_str)# 根据CUDA是否可用选择设备如果可用则使用cuda否则使用cpudevice torch.device(cuda if torch.cuda.is_available() else cpu)# 依内存情况自动选择主gpu
# flag变量用于控制是否根据显存情况自动选择主GPU
# 如果flag为1则执行以下代码块
flag 1
if flag:# 定义一个函数get_gpu_memory用于获取GPU的显存情况def get_gpu_memory():import platformif Windows ! platform.system():import osos.system(nvidia-smi -q -d Memory | grep -A4 GPU | grep Free tmp.txt)memory_gpu [int(x.split()[2]) for x in open(tmp.txt, r).readlines()]os.system(rm tmp.txt)else:memory_gpu Falseprint(显存计算功能暂不支持windows操作系统)return memory_gpu# 调用get_gpu_memory函数获取显存情况如果显存可用则执行以下代码块gpu_memory get_gpu_memory()if gpu_memory:print(\ngpu free memory: {}.format(gpu_memory))# 根据显存情况对GPU列表进行排序取排序后的第一个GPU作为主GPU并设置环境变量CUDA_VISIBLE_DEVICESgpu_list np.argsort(gpu_memory)[::-1]gpu_list_str ,.join(map(str, gpu_list))os.environ.setdefault(CUDA_VISIBLE_DEVICES, gpu_list_str)device torch.device(cuda if torch.cuda.is_available() else cpu)class FooNet(nn.Module):def __init__(self, neural_num, layers3):# 初始化FooNet类继承自nn.Module用于构建神经网络模型super(FooNet, self).__init__()# 定义一个线性层列表用于存储多个线性层层数为layers个self.linears nn.ModuleList([nn.Linear(neural_num, neural_num, biasFalse) for i in range(layers)])def forward(self, x):# 前向传播方法输入参数为x输出结果为x经过多个线性层和ReLU激活函数后的结果print(\nbatch size in forward: {}.format(x.size()[0])) # 打印输入张量的batch sizefor (i, linear) in enumerate(self.linears): # 遍历线性层列表中的每个元素进行循环迭代x linear(x) # 将输入张量传入线性层进行计算得到输出结果xx torch.relu(x) # 对输出结果应用ReLU激活函数得到新的输出结果xreturn x # 返回新的输出结果xif __name__ __main__:# 如果是主程序运行则执行以下代码块batch_size 16 # 设置批量大小为16inputs torch.randn(batch_size, 3) # 生成一个形状为(batch_size, 3)的随机张量作为输入数据labels torch.randn(batch_size, 3) # 生成一个形状为(batch_size, 3)的随机张量作为标签数据inputs, labels inputs.to(device), labels.to(device)# modelnet FooNet(neural_num3, layers3)net nn.DataParallel(net)net.to(device)# trainingfor epoch in range(1):outputs net(inputs)print(model outputs.size: {}.format(outputs.size()))print(CUDA_VISIBLE_DEVICES :{}.format(os.environ[CUDA_VISIBLE_DEVICES]))print(device_count :{}.format(torch.cuda.device_count()))打印结果
4.2 torch.distributed加速并行训练
DataParallel: 单进程控制多GPU DistributedDataParallel: 多进程控制多GPU一起训练模型
和单进程训练不同的是多进程训练需要注意一下事项
在喂数据的时候一个batch被分到了多个进程每个进程在取数据的时候要确保拿到的是不同的数据DistributedSampler要告诉每个进程自己是谁使用哪块GPUargs.local_rank在做BN的时候注意同步数据。
使用方式 在多进程的启动方面我们无需自己手写multiprocess进行一系列复杂的CPU、GPU分配任务PyTorch为我们提供了一个很方便的启动器torch.distributed.launch用于启动文件所以我们运行训练代码的方式就变成这样
CUDA_VISIBLE_DEVICES0,1,2,3 python -m torch.distributed.launch --nproc_per_node4 main.py初始化
在启动器为我们启动python脚本后在执行过程中启动器会将当前进行的index通过参数传递给python我们可以这样获得当前进程的index即通过参数local_rank来告诉我们当前进程使用的是哪个GPU用于我们在每个进程中指定不同的device:
def parse():parser argparse.ArgumentParser()parser.add_argument(--local_rank, typeint, default0, helpnode rank for distributed training)args parser.parse_args()return argsdef main():args parse()torch.cuda.set_device(args.local_rank)torch.distributed.init_process_group(nccl,init_methodenv://)device torch.device(fcuda:{args.local_rank})其中torch.distributed.init_process_group用于初始化GPU通信方式NCLL和参数的获取方式env代表通过环境变量。使用init_process_group设置GPU之间通信使用的后端和端口通过NCCL实现GPU通信
Dataloader
在我们初始化data_loader的时候需要使用到torch.utils.data.distributed.DistributedSampler这个特性
train_sampler torch.utils.data.distributed.DistributedSampler(train_dataset)
train_loader torch.utils.data.DataLoader(train_dataset, batch_size..., samplertrain_sampler)这样就能给每个进程一个不同的sampler告诉每个进程自己分别取哪些数据
模型的初始化 和nn.DataParallel的方式一样
model torch.nn.parallel.DistributedDataParallel(model, device_ids[args.local_rank])使用DistributedDataParallel包装模型, 它能帮助我们为不同GPU上求得的提取进行all reduce(即汇总不同GPU计算所得的梯度并同步计算结果)。all reduce 后不同GPU中模型的梯度均为all reduce之前各GPU梯度的均值。
5、gpu总结
我们在模型训练当中想要提高训练速率需要在以下三个地方添加gpu
将模型放到gpu上resnet18_ft.to(device)训练过程中数据 inputs, labels inputs.to(device), labels.to(device)验证过程中数据 inputs, labels inputs.to(device), labels.to(device)
常见的gpu报错 报错1 RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU -only machine, please use torch.load with map_locationtorch.device(‘cpu’) to map your storages to the CPU. 解决 torch.load(path_state_dict, map_location“cpu”) 报错2RuntimeError: Error(s) in loading state_dict for FooNet: Missing key(s) in state_dict: “linears.0.weight”, “linears.1.weight”, “linears.2.weight”. Unexpected key(s) in state_dict: “module.linears.0.weight”, “module.linears.1.weight”, “module.linears.2.weight”. 解决 from collections import OrderedDict new_state_dict OrderedDict() for k, v in state_dict_load.items (): namekey k[7:] if k.startswith(‘module.’) else k new_state_dict[namekey] v 文章转载自: http://www.morning.nmpdm.cn.gov.cn.nmpdm.cn http://www.morning.rblqk.cn.gov.cn.rblqk.cn http://www.morning.cnkrd.cn.gov.cn.cnkrd.cn http://www.morning.gchqy.cn.gov.cn.gchqy.cn http://www.morning.mlpmf.cn.gov.cn.mlpmf.cn http://www.morning.skksz.cn.gov.cn.skksz.cn http://www.morning.hphqy.cn.gov.cn.hphqy.cn http://www.morning.rfrx.cn.gov.cn.rfrx.cn http://www.morning.wcjgg.cn.gov.cn.wcjgg.cn http://www.morning.tpnx.cn.gov.cn.tpnx.cn http://www.morning.ptslx.cn.gov.cn.ptslx.cn http://www.morning.ywndg.cn.gov.cn.ywndg.cn http://www.morning.ysmw.cn.gov.cn.ysmw.cn http://www.morning.sjqpm.cn.gov.cn.sjqpm.cn http://www.morning.kyzxh.cn.gov.cn.kyzxh.cn http://www.morning.rtmqy.cn.gov.cn.rtmqy.cn http://www.morning.kjmcq.cn.gov.cn.kjmcq.cn http://www.morning.bfbl.cn.gov.cn.bfbl.cn http://www.morning.rzmsl.cn.gov.cn.rzmsl.cn http://www.morning.msgcj.cn.gov.cn.msgcj.cn http://www.morning.sjwqr.cn.gov.cn.sjwqr.cn http://www.morning.wmfr.cn.gov.cn.wmfr.cn http://www.morning.tjndb.cn.gov.cn.tjndb.cn http://www.morning.beiyishengxin.cn.gov.cn.beiyishengxin.cn http://www.morning.kzcfr.cn.gov.cn.kzcfr.cn http://www.morning.wqsjx.cn.gov.cn.wqsjx.cn http://www.morning.wdprz.cn.gov.cn.wdprz.cn http://www.morning.khxyx.cn.gov.cn.khxyx.cn http://www.morning.tqxtx.cn.gov.cn.tqxtx.cn http://www.morning.ycwym.cn.gov.cn.ycwym.cn http://www.morning.rgqnt.cn.gov.cn.rgqnt.cn http://www.morning.rsjf.cn.gov.cn.rsjf.cn http://www.morning.cczzyy.com.gov.cn.cczzyy.com http://www.morning.rmkyb.cn.gov.cn.rmkyb.cn http://www.morning.qqxmj.cn.gov.cn.qqxmj.cn http://www.morning.gtjkh.cn.gov.cn.gtjkh.cn http://www.morning.lqypx.cn.gov.cn.lqypx.cn http://www.morning.byzpl.cn.gov.cn.byzpl.cn http://www.morning.yrnll.cn.gov.cn.yrnll.cn http://www.morning.ggnrt.cn.gov.cn.ggnrt.cn http://www.morning.mbfkt.cn.gov.cn.mbfkt.cn http://www.morning.pwsnr.cn.gov.cn.pwsnr.cn http://www.morning.tckxl.cn.gov.cn.tckxl.cn http://www.morning.rszt.cn.gov.cn.rszt.cn http://www.morning.lzqtn.cn.gov.cn.lzqtn.cn http://www.morning.zlchy.cn.gov.cn.zlchy.cn http://www.morning.wclxm.cn.gov.cn.wclxm.cn http://www.morning.yltnl.cn.gov.cn.yltnl.cn http://www.morning.trrd.cn.gov.cn.trrd.cn http://www.morning.bpmtg.cn.gov.cn.bpmtg.cn http://www.morning.hrhwn.cn.gov.cn.hrhwn.cn http://www.morning.myzfz.com.gov.cn.myzfz.com http://www.morning.fmrd.cn.gov.cn.fmrd.cn http://www.morning.spwm.cn.gov.cn.spwm.cn http://www.morning.xhsxj.cn.gov.cn.xhsxj.cn http://www.morning.vjwkb.cn.gov.cn.vjwkb.cn http://www.morning.qgghj.cn.gov.cn.qgghj.cn http://www.morning.irqlul.cn.gov.cn.irqlul.cn http://www.morning.mkxxk.cn.gov.cn.mkxxk.cn http://www.morning.ksggr.cn.gov.cn.ksggr.cn http://www.morning.bzqnp.cn.gov.cn.bzqnp.cn http://www.morning.djmdk.cn.gov.cn.djmdk.cn http://www.morning.bxrqf.cn.gov.cn.bxrqf.cn http://www.morning.ryxbz.cn.gov.cn.ryxbz.cn http://www.morning.xrrbj.cn.gov.cn.xrrbj.cn http://www.morning.rgkd.cn.gov.cn.rgkd.cn http://www.morning.rkdzm.cn.gov.cn.rkdzm.cn http://www.morning.jjnql.cn.gov.cn.jjnql.cn http://www.morning.xxrgt.cn.gov.cn.xxrgt.cn http://www.morning.hqwxm.cn.gov.cn.hqwxm.cn http://www.morning.hqjtp.cn.gov.cn.hqjtp.cn http://www.morning.ngpdk.cn.gov.cn.ngpdk.cn http://www.morning.ycmpk.cn.gov.cn.ycmpk.cn http://www.morning.hpkr.cn.gov.cn.hpkr.cn http://www.morning.cpktd.cn.gov.cn.cpktd.cn http://www.morning.kljhr.cn.gov.cn.kljhr.cn http://www.morning.jfwbr.cn.gov.cn.jfwbr.cn http://www.morning.smzr.cn.gov.cn.smzr.cn http://www.morning.nqlkb.cn.gov.cn.nqlkb.cn http://www.morning.lthtp.cn.gov.cn.lthtp.cn