以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

相关文章

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

Golang如何用gorm实现分页的功能

《Golang如何用gorm实现分页的功能》:本文主要介绍Golang如何用gorm实现分页的功能方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景go库下载初始化数据【1】建表【2】插入数据【3】查看数据4、代码示例【1】gorm结构体定义【2】分页结构体