以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行

本文主要是介绍以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行

  • 1.创建Mixtral-8x7B配置文件
  • 2.测试代码

本文以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行
主要步骤:

  • 1.分析网络结构,确定拆分规则:
    第一部分:embed_tokens+MixtralDecoderLayer[:8]
    第二部分:MixtralDecoderLayer[8:16]
    第三部分:MixtralDecoderLayer[16:24]
    第四部分:MixtralDecoderLayer[24:32]+norm+lm_head
  • 2.因为,MixtralDecoderLayer要求输入attention_mask,position_ids
    为此增加一个LayerAdapterModule,根据输入生成attention_mask,position_ids
  • 3.增加SubLayer把上面切分后的模块组装起来
  • 4.CPU上运行原始模型推理以及切分后模型的推理,确认结果一致
  • 5.GPU上4卡推理,每个rank算自己的那一部分,采用异步p2p,充分overlap,最后一个rank的输出为最终的输出

1.创建Mixtral-8x7B配置文件

tee ./config.json <<-'EOF'
{"architectures": ["MixtralForCausalLM"],"attention_dropout": 0.0,"bos_token_id": 1,"eos_token_id": 2,"hidden_act": "silu","hidden_size": 1024,"initializer_range": 0.02,"intermediate_size": 4096,"max_position_embeddings": 1024,"model_type": "mixtral","num_attention_heads": 32,"num_experts_per_tok": 2,"num_hidden_layers": 32,"num_key_value_heads": 8,"num_local_experts": 8,"output_router_logits": false,"rms_norm_eps": 1e-05,"rope_theta": 1000000.0,"router_aux_loss_coef": 0.02,"sliding_window": 128,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.36.0.dev0","use_cache": true,"vocab_size": 32000
}
EOF

2.测试代码

tee open_model.py <<-'EOF'
import torch
import os
import numpy as np
import time
from accelerate import init_empty_weights
import json
import torch.distributed as dist
from collections import OrderedDict
from safetensors import safe_open
from safetensors.torch import save_file, load_file
from transformers import MixtralForCausalLM, MixtralConfig
from transformers.models.mixtral.modeling_mixtral import MixtralDecoderLayer
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
from thop import profile
np.set_printoptions(precision=3)class EmptyModule(torch.nn.Module):'''用于tensor切分'''def __init__(self):super(EmptyModule, self).__init__()passdef forward(self,x,*args):return x[0]class LayerAdapterModule(torch.nn.Module):'''为每一个子图的输入生成attention_mask和position_ids'''def __init__(self,config):super(LayerAdapterModule, self).__init__()self.config=configdef forward(self,x):past_key_values_length = 0batch_size, seq_length,_ = x.shapeposition_ids = torch.arange(past_key_values_length, seq_length + past_key_values_length, dtype=torch.long)position_ids = position_ids.unsqueeze(0).view(-1, seq_length)attention_mask = _prepare_4d_causal_attention_mask(None,(batch_size, seq_length),x,past_key_values_length,sliding_window=self.config.sliding_window)return (x,attention_mask.to(x.device),position_ids.to(x.device))class SubLayer(torch.nn.Module):'''每一个rank计算的子图'''def __init__(self,pre=None,adapter=None,layers=None):super(SubLayer, self).__init__()self.config=configself.pre=preself.adapter=adapterself.layers=torch.nn.ModuleList(layers)def forward(self,x):if self.pre:x=self.pre(x)if self.adapter:x,attention_mask,position_ids=self.adapter(x)for layer in self.layers:if isinstance(layer,MixtralDecoderLayer):x=layer(x,attention_mask,position_ids)else:x=layer(x)return x# 1.模型初始化
config=MixtralConfig.from_pretrained("./config.json")
with init_empty_weights():model = MixtralForCausalLM(config).half()buffer_dict = {}
for name, param in model.named_buffers():buffer_dict[name] = param.clone()with open("Mixtral-8x7B/model.safetensors.index.json", "r") as file:index_data = json.load(file)weight_files = index_data.get('weight_map', [])
state_dict = {}
for k,v in weight_files.items():weights_path = os.path.join("Mixtral-8x7B", v)with safe_open(weights_path, framework="pt") as f:for k in f.keys():state_dict[k] = f.get_tensor(k)model=model.to_empty(device="cpu")
model.load_state_dict(state_dict, strict=True)
for name, param in model.named_buffers():param.copy_(buffer_dict[name])model=model.float()# 2.生成输入
torch.manual_seed(2)
example_input=torch.randint(0,32000,(1,128)).to("cpu")# 3.将模型切分成4块
divided=[]
block_size=len(model.model.layers)//4  
offset=0submodules=[]
for i,m in enumerate(model.model.layers[:block_size]):submodules.append(m)submodules.append(EmptyModule())
divided.append(SubLayer(model.model.embed_tokens,LayerAdapterModule(config),submodules))
offset+=block_sizesubmodules=[]
for i,m in enumerate(model.model.layers[offset:offset+block_size]):submodules.append(m)submodules.append(EmptyModule())
divided.append(SubLayer(None,LayerAdapterModule(config),submodules))
offset+=block_sizesubmodules=[]
for i,m in enumerate(model.model.layers[offset:offset+block_size]):submodules.append(m)submodules.append(EmptyModule())
divided.append(SubLayer(None,LayerAdapterModule(config),submodules))
offset+=block_sizesubmodules=[]
for i,m in enumerate(model.model.layers[offset:]):submodules.append(m)submodules.append(EmptyModule())
submodules.append(model.model.norm)
submodules.append(model.lm_head)
divided.append(SubLayer(None,LayerAdapterModule(config),submodules))# 4.初始化分布式环境
dist.init_process_group(backend='nccl')
world_size = torch.distributed.get_world_size()
rank=torch.distributed.get_rank()
local_rank=int(os.environ['LOCAL_RANK'])# 5.运行CPU上的推理
if local_rank==world_size-1:output=model(example_input)output=output.logits.detach().reshape(-1).cpu().numpy()[:8]print("baseline:",output)for i in range(4):submodule=divided[i].float().to("cpu")example_input=submodule(example_input)dump=example_input.detach().reshape(-1).cpu().numpy()[:8]output=example_input.detach().reshape(-1).cpu().numpy()[:8]print("by layer:",output)torch.cuda.set_device(local_rank)
device=f"cuda:{local_rank}"example_input=example_input.to(device)
submodule=divided[local_rank].half().to(device)# 6.运行设备上的推理及吞吐测试
sreq=None
ts=[]
dist.barrier()epoch=64
t0=time.time()
for epoch in range(epoch):if sreq is not None and not sreq.is_completed():sreq.wait()sreq=Noneif local_rank!=0:tensor_size = torch.empty((3,), dtype=torch.int64).to(device)torch.distributed.recv(tensor_size,local_rank-1)example_input = torch.empty(tensor_size.tolist()).to(device).half()torch.distributed.recv(example_input,local_rank-1)        else:torch.manual_seed(1)    output=submodule(example_input)if epoch==0:flops, params = profile(submodule, inputs=(example_input,))print(f"{rank} 模型的FLOPs: {flops:,} 模型的参数量: {params:,}")  if local_rank<world_size-1:        tensor_size = torch.tensor(output.size(), dtype=torch.int64).to(device)torch.distributed.isend(tensor_size,local_rank+1)sreq=torch.distributed.isend(output,local_rank+1)#torch.distributed.send(output,local_rank+1)elif local_rank==world_size-1:ts.append(time.time())dist.barrier()
t1=time.time()time.sleep(0.2*local_rank)
if local_rank==world_size-1:ts=ts[len(ts)//2:]print("latency:{:.2f} qps0:{:.2f} qps1:{:.2f}".format(ts[1]-ts[0],len(ts)/(ts[-1]-ts[0]),epoch/(t1-t0)))output=output.detach().reshape(-1).cpu().numpy()[:8]print(output)
EOF
python -m torch.distributed.run --nnodes=1 --nproc_per_node=4  open_model.py

这篇关于以MixtralForCausalLM为例,演示如何不依赖框架实现pipeline并行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1071439

相关文章

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU